我的Django项目中有三个模型:
class Model1(models.Model):
name = models.CharField(max_length=10)
class Model2(models.Model):
name = models.CharField(max_length=10)
class OneToTwo(models.Model):
one = models.ForeignKey(Model1)
two = models.ForeignKey(Model2)
extra_field_necessitating_intermediate_model = models.IntegerField(default=0)
我正在使用Django REST Framework为这些模型构建API,我有Model1和Model2的序列化器:
class Model1Serializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Model1
fields = ('url', 'name')
class Model2Serializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Model2
fields = ('url', 'name')
......到目前为止,非常好。当我想在Model1序列化器中嵌套Model2时会出现问题。我可以创造 包含Model2数据的OneToTwo实体的中间序列化程序:
class TwosSerializer(serializers.HyperlinkedModelSerializer):
id = serializers.ReadOnlyField(source='two.id')
name = serializers.ReadOnlyField(source='two.name')
class Meta:
model = OneToTwo
fields = ('url', 'id', 'name')
class Model2Serializer(serializers.HyperlinkedModelSerializer):
twos = TwosSerializer(source='onetotwo_set', many=True)
class Meta:
model = Model2
fields = ('url', 'name', 'twos')
...但url
上的TwosSerializer
字段是OneToTwo
实体的字段,而不是相关Model2
实体的字段。
我想要的是内部序列化程序的url
字段是Model2.objects.get(pk=two.id)
的URL
关系中的每个two
对象。
天真的尝试是使用url
类创建HyperlinkedIdentityField
字段定义:
# this is within the TwosSerializer class above...
url = serializers.HyperlinkedIdentityField(view_name='model2-detail', lookup_value='two.id')
...但这会导致此错误:
'OneToTwo' object has no attribute 'two.id'
如何正确构建通过我不想要的中间模型的实体的URL 在API中公开?