我该如何将“示例对象”映射到网址:
另外,我不明白为什么在(Api View)中传递用户而不是user_id到
website.com/api/<user>/<slug>
?我遇到了invalid literal for int() with base 10: 'username'
错误,所以我明白需要使用用户ID才能映射到对象,这是因为如果我使用用户ID(整数)(网址: website.com/api/<user_id>/<slug>
),而不仅仅使用用户/用户名(字符串),我就可以映射到对象。是否有一种方法可以覆盖默认值,从而在从user_id(整数)映射到对象时将其更改为其他字段,比如user(字符串)?另外,我不明白为什么在(Api View)中传递用户而不是user_id到
def get_object
无法解决此问题。
网址
urlpatterns = [
url(r'^api/(?P<user>\w+)/(?P<slug>[\w-]+)/$', ExampleDetailAPIView.as_view(), name='example'),
]
API视图
class ExampleDetailAPIView(RetrieveAPIView):
queryset = Example.objects.all()
serializer_class = ExampleDetailSerializer
def get_object(self):
user = self.kwargs.get('user')
slug = self.kwargs.get('slug')
return Example.objects.get(user=user, slug=slug)
def get_serilizer_context(self, *args, **kwargs):
return {'request': self.request}
序列化器
class ExampleDetailSerializer(HyperlinkedModelSerializer):
url = serializers.SerializerMethodField()
class Meta:
model = Example
fields = [
'url',
]
def get_url(self, obj):
request = self.context.get('request')
return obj.get_api_url(request=request)
模型
class Example(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1)
example_name = models.CharField(max_length=100)
slug = models.SlugField(max_length=100, blank=True)
class Meta:
unique_together = ('user', 'slug')
def get_api_url(self, request=None):
return api_reverse('example-api:example', kwargs={'user': self.user.username, 'slug': self.slug}, request=request)
@receiver(pre_save, sender=Example)
def pre_save_example_slug_receiver(sender, instance, *args, **kwargs):
slug = slugify(instance.example_name)
instance.slug = slug