gpt4 book ai didi

python - 序列化器 - Django REST 框架(AttributeError : Got AttributeError when attempting to get a value for field `user` on serializer)

转载 作者:行者123 更新时间:2023-12-01 08:57:29 33 4
gpt4 key购买 nike

AttributeError:尝试在序列化器 UserKeywordSerializer 上获取字段 user 的值时出现 AttributeError。序列化程序字段可能命名不正确,并且与 QuerySet 实例上的任何属性或键不匹配。

models.py

class Keyword(models.Model):
name=models.CharField(max_length=500,unique=True)
image = models.ImageField(upload_to='keywords/', blank=True, null=True)
mood=models.ManyToManyField(Mood,blank=True)
def __str__(self):
return str(self.name)

class UserKeyword(models.Model):
keywords=models.ManyToManyField(Keyword)
count=models.IntegerField(blank=True,null=True,default=0)
user=models.ForeignKey(User,on_delete=models.CASCADE)
def __str__(self):
return str(self.id)

序列化器.py

class KeywordsSerializer(serializers.ModelSerializer):
class Meta:
model = Keyword
fields ='__all__'

class UserKeywordSerializer(serializers.ModelSerializer):
keywords = KeywordsSerializer( read_only=True,many=True)

class Meta:
model = UserKeyword
fields = '__all__'

views.py

top_keywords=UserKeyword.objects.filter(user_id=request.user.id).select_related().order_by('-count')
user_serializer=UserKeywordSerializer(top_keywords).data
print(user_serializer)

最佳答案

top_keywords=UserKeyword.objects.filter(user_id=request.user.id).select_related().order_by('-count')

user_serializer=UserKeywordSerializer(top_keywords, many=True).data

top_keywords 是查询集,因此您应该将 many=True 添加到序列化器,请参阅 Dealing with multiple objects .

关于python - 序列化器 - Django REST 框架(AttributeError : Got AttributeError when attempting to get a value for field `user` on serializer),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52695868/

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