简体   繁体   English

DRF 将模型中的单个字段关联起来

[英]DRF relate single field from model

Yes, I know there are a lot of questions about DRF serializer relations that are already answered.是的,我知道有很多关于 DRF 序列化器关系的问题已经得到解答。 But non of them could help me or I'm to dump to get it...但是他们中没有一个可以帮助我,否则我将倾倒以获得它......

I have the following models:我有以下型号:

class User(models.Model):
    id = models.IntegerField(primary_key=True)
    name = models.CharField(max_length=30)
    ...

class Person(models.Model):
    id = models.IntegerField(primary_key=True)
    person_id = models.IntegerField()
    birthdate = models.DateTimeField(blank=True, null=True)
    ...

Now I want the birthdate field from Person in User like this:现在我想要来自Person in Userbirthdate字段,如下所示:

{
    "id": 397,
    "name": "name",
    "birthdate": "2015-11-11T00:00:00Z",
    ...
}

So I did this:所以我这样做了:

class UserSerializer(serializers.ModelSerializer):
    birthdate = serializers.SerializerMethodField()

    class Meta:
        model = User

    def get_birthdate(self, obj):
        person = PersonSerializer(Person.objects.get(person_id=obj.pk)).data
        return person['birthdate']

It works yea but there has to be a better way.它有效,但必须有更好的方法。 I have multiple fields I want to relate in this way and the result would be awkward code so please help me!我想以这种方式关联多个领域,结果将是尴尬的代码,所以请帮助我!

Thanks again to dhke.再次感谢dhke。 He helped me in the comments to find the answer to my question.他在评论中帮助我找到了我问题的答案。

The only thing I had to do is adding a OneToOneField to Person :我唯一要做的就是将OneToOneField添加到Person

class Person(models.Model):
    id = models.IntegerField(primary_key=True)
    person_id = models.OneToOneField(User, related_name='person')
    birthdate = models.DateTimeField(blank=True, null=True)
    ...

Then add the following field to UserSerializer :然后将以下字段添加到UserSerializer

birthdate = serializers.DateTimeField(source='person.birthdate')

And that is the whole magic.这就是整个魔法。

(I love DRF!) (我爱 DRF!)

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

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