Django rest中的通用关系

时间:2019-03-08 07:28:43

标签: django django-models django-rest-framework django-views django-generic-relations

问题

我想用地址创建学生。我该如何在Django中编写REST API。

地址和学生

class Address(models.Model):
    address = models.CharField(max_length=100, null=False, blank=False)
    land_mark = models.CharField(max_length=100, null=True, blank=True)
    city = models.CharField(max_length=100, null=True, blank=True)
    state = models.CharField(max_length=100, null=True, blank=True)
    pin_code = models.CharField(max_length=100, null=True, blank=True)
    latitude = models.FloatField(default=0.0)
    longitude = models.FloatField(default=0.0)
    geo_code = models.CharField(max_length=100, null=True, blank=True)
    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, 
                                    null=True)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id')

 class Student(models.Model):
    name = model.CharField(max_length=100, null=False, blank=False)
    address = GenericRelation(Address)
    def __str__(self):
        return self.name

序列化器

class AddressSerializer(serializers.ModelSerializer):
    class Meta:
        model = Address
        fields = "__all__"


 class StuddentSerializer(serializers.ModelSerializer):
       class Meta:
            model = Student
            fields = "__all__"

API视图

class AddressApiView(ListCreateAPIView):
    queryset = Address.objects.all()
    serializer_class = AddressSerializer

 class StudentApiView(ListCreateAPIView):
    queryset = Student.objects.all()
    serializer_class = StuddentSerializer

我如何获得我的创建/查看学生?

1 个答案:

答案 0 :(得分:0)

您可以尝试使用第三方应用rest-framework-generic-relation link