简体   繁体   English

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

[英]In DRF(django-rest-framework), If model has two foreignkeyfield, is it possible to serialize?

I made django project through DRF. 我通过DRF制作了django项目。

On my struggling with DRF, I getting wonder that it is possible to serializing these models. 在为DRF奋斗的过程中,我很奇怪是否可以序列化这些模型。

models.py 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

There are two ForeignKey field in Comment model, i think it is maybe the reason serializer.py is very hard to deal with. Comment模型中有两个ForeignKey字段,我认为这可能是serializer.py很难处理的原因。

serializers.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)

I thought comments = serializers.PrimaryKeyRelatedField(many=True, read_only=True) have to be placed in class PostSerializer(serializers.ModelSerializer): also, but when i placed as i thought, there comes error AssertionError at /posts/ The field 'comments' was declared on serializer PostSerializer, but has not been included in the 'fields' option. 我以为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.出现错误AssertionError at /posts/ The field 'comments' was declared on serializer PostSerializer, but has not been included in the 'fields' option. so when i put 'comments' in ther field like 所以当我在诸如

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

then, -> AttributeError at /posts/ 'Post' object has no attribute 'comments' is occurred. 然后, AttributeError at /posts/ 'Post' object has no attribute 'comments' -> AttributeError at /posts/ 'Post' object has no attribute 'comments'发生。

What is my fault? 我怎么了

Because I want make android app that user can read a post and comments 'related with the post' at the same time(like almost community websites, reddit, facebook...), serializers.py i posted is not enough. 因为我要使Android应用程序使用户可以同时阅读帖子和与帖子“相关”的评论(例如几乎社区网站,reddit,facebook ...),所以我发布的serializers.py是不够的。 serializers.py i posted is not seems to be sufficient for reflecting relation between post and comment. 我发布的serializers.py似乎不足以反映发布和评论之间的关系。

Are there problem with comment model? 评论模型有问题吗? Or am i wrong? 还是我错了?

I'm new, novice at programming, Please teach me. 我是新手,编程新手,请教我。

Thanks for reading. 谢谢阅读。

There is nothing wrong, you are just accessing the wrong attributes. 没错,您只是在访问错误的属性。 If you look at your models, you define a related name to posts: 如果您查看模型,则可以为帖子定义一个相关名称:

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

So, when you write your serializer, the "field" you should be accessing should be the related name instead of comments. 因此,在编写序列化程序时,您应该访问的“字段”应该是相关名称,而不是注释。 Change the serializer to: 将序列化器更改为:

class PostSerializer(serializers.ModelSerializer):
    related_comments = serializers.PrimaryKeyRelatedField(many=True, read_only=True)
    class Meta:
        model = Post
        fields = ('id', 'author', 'title', 'text', 'point', 'related_comments')

您可以使用嵌套关系

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM