好吧,我正在尝试跟Django Rest Framework保持联系。
这是一个简化的模型:
class Model1(models.Model):
name = models.CharField(max_length=20)
owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
class Model2(models.Model):
title = models.CharField(max_length=12, null=True, blank=True)
model1 = models.ForeignKey(Model1, on_delete=models.CASCADE)
和序列化器:
class Model1Serializer(serializers.ModelSerializer):
class Meta:
model = Model1
fields = '__all__'
class Model2Serializer(serializers.ModelSerializer):
class Meta:
model = Model2
fields = '__all__'
我想从Model2中访问所有者属性,例如电子邮件...
在没有DRF的情况下,在标准模板中,我会这样做:
{{ instanceOfModel2.model1.owner.email }}
这将遵循关系。
您知道我如何使用Django DRF实现这一目标吗?
我看着https://www.django-rest-framework.org/api-guide/relations/ 但是我想要的是相反的方式...而且我不想通过REST API公开Django用户模型。...
答案 0 :(得分:2)
您可以使用点分符号来定义新字段以及source
属性:
class Model2Serializer(serializers.ModelSerializer):
email = serializers.EmailField(source='model1.owner.email', read_only=True)
class Meta:
model = Model2
fields = '__all__'
答案 1 :(得分:0)
您必须创建一个用户序列化程序,并将这些序列化程序相互关联。
User = get_user_model()
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = '__all__'
class Model1Serializer(serializers.ModelSerializer):
owner = UserSerializer()
class Meta:
model = Model1
fields = '__all__'
class Model2Serializer(serializers.ModelSerializer):
model1 = Model1Serializer()
class Meta:
model = Model2
fields = '__all__'
答案 2 :(得分:0)
如果您希望该字段为read only
:
class Model2Serializer(serializers.ModelSerializer):
email = serializers.SerializerMethodField()
class Meta:
model = Model2
fields = ('email', ...)
def get_email(self, obj):
return obj.model1.owner.email