在DRF(django-rest-framework)中,如果模型有两个foreignkeyfield,是否可以序列化?

时间:2016-08-03 19:33:43

标签: python django django-rest-framework

我通过DRF制作了django项目。

在我与DRF的斗争中,我开始怀疑是否可以序列化这些模型。

models.py

class Post(models.Model):
    author = models.ForeignKey(User, related_name='related_postwriter')
    title = models.CharField(max_length=200, blank = False)
    text = models.TextField(blank = True)
    created_date = models.DateTimeField(
        default=timezone.now
        )
    point = models.PointField(null=False, blank=True)

    def __str__(self):              # __unicode__ on Python 2
        return self.title

class Comment(models.Model):
    post = models.ForeignKey('blog.Post', related_name='related_comments')
    author = models.ForeignKey(User, related_name='related_commentwriter')
    text = models.TextField(max_length=500)
    created_date = models.DateTimeField(default=timezone.now)

    def __str__(self):
        return self.text

Comment模型中有两个ForeignKey字段,我想这可能是serializer.py很难处理的原因。

serializers.py

class UserSerializer(serializers.ModelSerializer):
    posts = serializers.PrimaryKeyRelatedField(many=True, read_only=True)
    comments = serializers.PrimaryKeyRelatedField(many=True, read_only=True)
    class Meta:
        model = User
        fields = ('id', 'username', 'email', 'posts')

class PostSerializer(serializers.ModelSerializer):
    class Meta:
        model = Post
        fields = ('id', 'author', 'title', 'text', 'point')
    def create(self, validated_data):
        validated_data['author'] = self.context['request'].user
        return super(PostSerializer, self).create(validated_data)


class CommentSerializer(serializers.ModelSerializer):
    class Meta:
        model = Comment
        fields = ('id', 'post', 'author', 'text')
    def create(self, validated_data):
        validated_data['author'] = self.context['request'].user
        return super(CommentSerializer, self).create(validated_data)

我想comments = serializers.PrimaryKeyRelatedField(many=True, read_only=True) 也必须放在class PostSerializer(serializers.ModelSerializer):中,但是当我按照我的想法放置时,会出现错误AssertionError at /posts/ The field 'comments' was declared on serializer PostSerializer, but has not been included in the 'fields' option.,所以当我发表评论时#39}在像

这样的领域
class PostSerializer(serializers.ModelSerializer):
    comments = serializers.PrimaryKeyRelatedField(many=True, read_only=True)
    class Meta:
        model = Post
        fields = ('id', 'author', 'title', 'text', 'point', 'comments')

然后, - >发生AttributeError at /posts/ 'Post' object has no attribute 'comments'

我的错是什么?

因为我想制作Android应用,用户可以阅读帖子和与帖子相关的评论'在同一时间(像几乎社区网站,reddit,脸书...),我发布的 serializers.py 是不够的。我发布的 serializers.py 似乎不足以反映帖子和评论之间的关系。

评论模型有问题吗?或者我错了吗?

我是新手,编程新手,请教我。

感谢阅读。

2 个答案:

答案 0 :(得分:2)

没有错,你只是访问错误的属性。如果您查看模型,请为帖子定义相关名称:

@json(decodeBase64(triggerBody()['ContentData']))

因此,当您编写序列化程序时,您应该访问的“字段”应该是相关名称而不是注释。将序列化程序更改为:

post = models.ForeignKey('blog.Post', related_name='related_comments')

答案 1 :(得分:1)

您可以使用Nested relationships