django rest框架更改主键以使用unqiue字段 [英] django rest framework change primary key to use a unqiue field
问题描述
我有一个名为 GameProfile
的模型,它与 User
模型是一对一的关系。我在所有设计中使用了 HyperlinkedModelSerializer
。
I have a model which is called GameProfile
, which is a one to one relation with User
model. I used HyperlinkedModelSerializer
across all my design.
对于 GameProfile
,用户字段假设是查询的主键,它是唯一的,但我没有将其设置为主要关键。有没有办法更改django serializer的默认行为,指向 user__id
作为主键,并始终使用它来在详细视图中查看配置文件?
For the GameProfile
, the user field is suppose to be the primary key for querying, it is unique but I did not set it up as a primary key. Is there a way to change the default behavior of django serializer to point to user__id
as the primary key and always use it for retreiving the profile in the detail view?
class GameProfileSerializer(serializers.HyperlinkedModelSerializer):
"""
"""
user_pk = serializers.Field(source='user.id')
class Meta:
model = GameProfile
class GameProfileViewSet(viewsets.ModelViewSet):
"""
"""
queryset = GameProfile.objects.all()
serializer_class = GameProfileSerializer
def get_queryset(self):
""" get_queryset
"""
queryset = super(GameProfileViewSet, self).get_queryset()
if not queryset.exists():
raise Http404
if self.request.user.is_authenticated() and not self.request.user.is_superuser:
return queryset.filter(user=self.request.user)
return queryset
请告知,提前感谢:)
推荐答案
假设您的 GameProfile
模型看起来像:
Assuming your GameProfile
model looks like:
class GameProfile(models.Model)
user = models.OneToOneField('User')
序列化程序将是:
class GameProfileSerializer(serializers.HyperlinkedModelSerializer):
user_id = serializers.Field(source='user.id')
class Meta:
model = GameProfile
正确设置视图中的 .lookup_field
属性:
Set the .lookup_field
attribute on the view correctly:
lookup_field = 'user_id'
URL将是: p>
Url will be:
/gameprofile/<user_id>
这篇关于django rest框架更改主键以使用unqiue字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!