【发布时间】:2015-11-18 16:50:32
【问题描述】:
是的,我知道有很多关于 DRF 序列化程序关系的问题已经得到解答。但是他们都不能帮助我,否则我会倾倒去得到它......
我有以下型号:
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)
...
现在我想要 Person 中的 birthdate 字段在 User 中,如下所示:
{
"id": 397,
"name": "name",
"birthdate": "2015-11-11T00:00:00Z",
...
}
所以我这样做了:
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']
它有效,但必须有更好的方法。我想以这种方式关联多个字段,结果将是笨拙的代码,所以请帮助我!
【问题讨论】:
-
person_id不是ForeignKey(User)的任何原因? -
我已经试过了。但是我必须在序列化程序中做什么?
-
birthdate = DateTimeField(source="person_set.birthdate")应该可以解决问题,其中person_set需要是外键的related_name。有关详细信息,请参阅the documentation。您可能还想使用OneToOneField,因为目前每个用户可以有多个人。 -
Got AttributeError when attempting to get a value for field 'birthdate' on serializer 'UserSerializer'. The serializer field might be named incorrectly and not match any attribute or key on the 'User' instance. Original exception text was: 'RelatedManager' object has no attribute 'birthdate'.这就是我得到的 -
不要被胡须缠住,那么;-)。其实我想这个问题太晚了。简单外键上的
DateTimeField仅适用于many=True,因为该架构允许每个用户有多个人。使用OneToOneField解决了这个问题,也清理了架构。
标签: python django api rest django-rest-framework