Django Rest DRF - 当存在外键关系时,使用基于通用类的视图(CreateAPIView)的Post方法

时间:2017-08-23 10:52:10

标签: django rest post foreign-keys django-rest-framework

我目前在DRF api中有以下结构。

models.py

class Location(models.Model):
    name = models.CharField(max_length=64, unique=True)
    district = models.CharField(max_length=64, blank=True)
    division = models.CharField(max_length=64, blank=True)
    latitude = models.DecimalField(max_digits=9, decimal_places=3, blank=True)
    longitude = models.DecimalField(max_digits=9, decimal_places=3, blank=True)

class Event(models.Model):
    title = models.CharField(max_length=64)
    location = models.ForeignKey(Location, on_delete=models.CASCADE, blank=False, null=False)
    type = models.CharField(max_length=64, blank=True)
    max_quota = models.IntegerField(blank=True)
    min_cost = models.IntegerField(blank=True)
    duration_start = models.CharField(max_length=64, blank=True)
    duration_end = models.CharField(max_length=64, blank=True)

serializers.py

class LocationSerializer(serializers.ModelSerializer):
    class Meta:
        model = Location
        fields = ['name', 'district', 'division', 'latitude', 'longitude', ]

class ExperienceCreateSerializer(serializers.ModelSerializer):
    location = LocationSerializer(many=False)
    #location_id = serializers.PrimaryKeyRelatedField(read_only=True)

    class Meta:
        model = Experience
        fields = ['title', 'type', 'max_quota', 'min_cost', 'duration_start', 'duration_end', 'location', ]

views.py

class ExperienceCreate(generics.CreateAPIView):
    queryset = Experience.objects.all()
    serializer_class = ExperienceCreateSerializer

我的获取请求工作正常,但是当我想要POST到事件模型时,我总是会遇到某种错误。我已经尝试了很多东西,包括覆盖create方法,也尝试使用primarykeyfield。问题在于事件模型和序列化程序中的位置外键引用。我确实尝试了除此之外的一些事情,但唯一有意义的解决方案是覆盖create()方法。但是,没有任何效果。我不明白我错在哪里。

1 个答案:

答案 0 :(得分:0)

好吧,我找到了解决方法。如果已经创建了位置对象,那么我们需要做的是将位置作为PrimaryKeyRelatedField传递给序列化程序。注: write_only需要成为现实

location = serializers.PrimaryKeyRelatedField(queryset=Location.objects.all(), write_only=True)