序列化程序-Django REST框架(尝试在序列化程序上获取字段`user`的值时出现AttributeError:AttributeError)

时间:2018-10-08 05:27:18

标签: python django python-3.x django-rest-framework

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)

1 个答案:

答案 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