如何使用Model serializer在django-rest中序列化一对多关系?

时间:2016-10-04 19:18:16

标签: python serialization django-rest-framework one-to-many django-serializer

这些是我的模型和序列化程序。我想要问题模型的表示以及询问问题的人员列表。

我正在尝试这个:

@api_view(['GET', 'PATCH'])
def questions_by_id(request,user,pk):
    question = Question.objects.get(pk=pk)
    if request.method == 'GET':
        serializer = QuestionSerializer(question)
        return Response(serializer.data)

但我得到一个空字典({})。但是,当我从asked中移除QuestionSerializer字段时,我得到了Question的完整表示以及Places很好地序列化。我错过了什么?

class AskedToSerializer(serializers.ModelSerializer):
class Meta:
    model = AskedTo
    fields = ('to_user', 'answered')

class QuestionSerializer(serializers.ModelSerializer):
class Meta:
    model = Question
    places = PlaceSerializer(many=True, required=False)
    asked = AskedToSerializer(source='askedto_set', many=True)
    fields = ('id', 'created_on', 'title', 'places', 'answered','asked')
    extra_kwargs = {'created_by': {'read_only': True}}

class Question(BaseModel):
    title = models.CharField(max_length=200, null=False)
    places = models.ManyToManyField(Place, blank=True)
    answered = models.BooleanField(default=False)

class AskedTo(BaseModel):
    ques = models.ForeignKey(Question, on_delete=models.CASCADE)
    to_user = models.ForeignKey(settings.AUTH_USER_MODEL)
    replied = models.BooleanField(default=False)


class Place(models.Model):
    g_place_id = models.CharField(max_length=20,primary_key=True)
    json = models.TextField(null=True)
    name = models.CharField(max_length=40)

2 个答案:

答案 0 :(得分:8)

我明白了。有两个错误。

将此更改为

class AskedToSerializer(serializers.ModelSerializer):
class Meta:
    model = AskedTo
    fields = ('to_user', 'answered')

这(注意字段的变化,模型和序列化器上的字段不匹配)

class AskedToSerializer(serializers.ModelSerializer):
class Meta:
    model = AskedTo
    fields = ('to_user', 'replied')

其次,我需要在class Meta

之外定义任何额外的字段
class QuestionSerializer(serializers.ModelSerializer):
    places = PlaceSerializer(many=True, required=False)
    asked = AskedToSerializer(source='askedto_set', many=True)    
    class Meta:
        model = Question
        fields = ('id', 'created_on', 'title', 'places', 'answered','asked')
        extra_kwargs = {'created_by': {'read_only': True}}

请注意placesasked

定义的变化

答案 1 :(得分:1)

就我而言,我有这个 models.py

QName

然后我完成了 serializers.py

class Section(models.Model):
     title = models.CharField(max_length=500)
     description = models.TextField(blank=True)
     user = models.ForeignKey(Profile, related_name="sections", on_delete=models.CASCADE)

class Feed(models.Model):
     title = models.CharField(max_length=500)
     link_rss = models.URLField(max_length=500)
     link_web = models.URLField(max_length=500)
     description = models.TextField(blank=True)
     language = models.CharField(max_length=50, blank=True)
     logo = models.URLField(blank=True)

     sections = models.ManyToManyField(Section, related_name="feeds")