0

我有以下模型结构:

**models.py**

class Person(models.Model):
    .
    .
    contact = GenericRelation(Contact)


class Patient(Person):
    some other fields

创建患者时,我在序列化程序中执行以下操作:

**serializers.py**

class PatientSerializer(serializers.ModelSerializer):

    contact = ContactSerializer(many=True)

    class Meta:
        model = Patient
        fields = PersonSerializer.Meta.fields + ...


    def create(self, validated_data):
        if('contact' in validated_data):
            contact_data = validated_data.pop('contact')

        instance = Patient.objects.create(**validated_data)
        person = Person.objects.get(id=instance.person_ptr_id)

        if(contact_data):
            for contact in contact_data:
                Contact.objects.create(..., content_object=person)

这样,在 Contact 表中,它将直接引用 Person 基本模型。这样做的目的是我必须在 Person 上创建另一个类来继承这些联系人。

我在这种结构中遇到的问题是,对于患者视图,“联系人”始终为空:它从列表中返回以下内容并检索视图。可能只是调整查询集的问题吗?

“接触”: []

任何使此代码更好/结构的建议都受到欢迎。

提前致谢!

4

0 回答 0