AttributeError::尝试获取序列化程序user
上字段UserKeywordSerializer
的值时,出现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)
serializer.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)
答案 0 :(得分:1)
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。