gpt4 book ai didi

python - 将 PrimaryKeyRelatedField 替换为另一个字段

转载 作者:行者123 更新时间:2023-12-01 03:30:59 25 4
gpt4 key购买 nike

我的模型由 User 模型和 Present 模型组成。一个User可以有多个Present,但一个Present有一个唯一的User:

我的models.py是:

from django.db import models
from django.contrib.auth.models import User

class Present(models.Model):
name = models.CharField(max_length=15)
price = models.FloatField()
link = models.CharField(max_length=15)
isAlreadyBought = models.BooleanField()
user = models.ForeignKey(User, related_name='presents', on_delete=models.CASCADE)

我的serializers.py是:

from django.contrib.auth.models import User, Group
from rest_framework import serializers
from blog.models import Present, Location
from django.contrib.auth.models import User


class UserSerializer(serializers.ModelSerializer):

presents = serializers.PrimaryKeyRelatedField(many=True, queryset=Present.objects.all(), required=False)

class Meta:
model = User
fields = ('username', 'password', 'email', 'presents')

def create(self, validated_data):
user = super().create(validated_data)
if 'password' in validated_data:
user.set_password(validated_data['password'])
user.save()
return user



class PresentSerializer(serializers.ModelSerializer):

user = serializers.PrimaryKeyRelatedField(queryset=User.objects.all(), read_only=False, many=False)

class Meta:
model = Present
fields = ('name', 'link', 'price', 'isAlreadyBought', 'user')

def create(self, validated_data):
return Present.objects.create(**validated_data)

目前,如果我想获取与给定用户关联的所有礼物,我使用主键(在 views.py 中):

class PresentsOfUser(viewsets.ModelViewSet):
queryset = Present.objects.all().filter(user=33)
serializer_class = PresentSerializer

但是,我宁愿使用 Userusername 字段而不是主键。

我尝试过使用 SlugRelatedField 但我不确定这是实现我的目标的正确方法:

class PresentSerializer(serializers.ModelSerializer):

user = serializers.SlugRelatedField(queryset=User.objects.all(), slug_field='username', read_only=False, many=False)

class Meta:
model = Present
fields = ('name', 'link', 'price', 'isAlreadyBought', 'user')

def create(self, validated_data):
return Present.objects.create(**validated_data)

经过此修改,我现在使用以下 View 来获取 id33< 的用户 'Marcel'/:

class PresentsOfUser(viewsets.ModelViewSet):
queryset = Present.objects.all().filter(user='Marcel')
serializer_class = PresentSerializer

但在这种情况下,我得到:

ValueError: invalid literal for int() with base 10: 'Marcel'

但是,如果我将 user='Marcel' 替换为 user=33(如前所述),我会得到:

[{"name":"Nintendo","link":"fake_link","price":50.8,"isAlreadyBought":true,"user":"Marcel"},{"name":"Gamecube","link":"fake_link","price":50.8,"isAlreadyBought":true,"user":"Marcel"}]

其中用户字段现在是用户名,而不是用户的id

但是,我不明白为什么使用 user='Marcel' 过滤失败...

最佳答案

我最终覆盖了 get_queryset 方法,同时将 PrimaryKeyRelatedField 保留在我的序列化程序中(使用 user__username='Marcel' 作为 mishbah 的建议) :

class PresentsOfUser(viewsets.ModelViewSet):

serializer_class = PresentSerializer

def get_queryset(self):
"""
Optionally restricts the returned purchases to a given user,
by filtering against a `username` query parameter in the URL.
"""
queryset = Present.objects.all()
username = self.kwargs['user']
if username is not None:
queryset = queryset.filter(user__username=username)

if len(queryset) == 0:
raise Http404

return queryset

当用 SlugRelatedField 替换 PrimaryKeyRelatedField 时,它也适用:

user = serializers.SlugRelatedField(queryset=User.objects.all(), slug_field='username', read_only=False, many=False)

并在我的 Present 模型的 ForeignKey 中添加 to_field='username':

user = models.ForeignKey(User, related_name='presents', to_field='username', on_delete=models.CASCADE)

关于python - 将 PrimaryKeyRelatedField 替换为另一个字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40941200/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com