django rest_framework在CreateAPIView中选择foreignKey模型

时间:2018-04-24 13:42:21

标签: python django django-rest-framework

我想使用 django rest framework 创建新的ServiceArea实例,但无法弄清楚如何在{{1}中设置supplier foreignKey字段}。我尝试使用CreateApiView进行此操作,但是当我将PrimaryKeyRelatedField属性设置为等于queryset时,它会给出错误Supplier.objects.all()。我如何才能访问'ServiceArea' object has no attribute 'suppliers'中的suppliers?我的代码:

models.py

CreateApiView

serializers.py

class Supplier(models.Model):
    title = models.CharField('Название', max_length=60)
    email = models.EmailField(verbose_name='Почта')
    phone_number = models.CharField('Номер телефона', max_length=15)
    address = models.CharField('Адрес центрального офиса', max_length=120)

    class Meta:
        verbose_name = 'Поставщик'
        verbose_name_plural = 'Поставщики'

    def __str__(self):
        return self.title


class ServiceArea(models.Model):
    title = models.CharField('Название области', max_length=120)
    poly = geo_models.PolygonField('Область', null=True)
    supplier = models.ForeignKey(Supplier, related_name='areas', on_delete=models.CASCADE, null=True)

    class Meta:
        verbose_name = 'Сервисная зона'
        verbose_name_plural = 'Сервисные зоны'

    def __str__(self):
        return self.title

views.py

class SupplierSerializer(ModelSerializer):
    class Meta:
        model = Supplier
        fields = [
            'id',
       ]

class ServiceAreaSerializer(GeoFeatureModelSerializer):
    suppliers = PrimaryKeyRelatedField(many=True, queryset=Supplier.objects.all())

    class Meta:
        model = ServiceArea
        geo_field = 'poly'
        fields = [
            'id',
            'title',
            'suppliers',
        ]

1 个答案:

答案 0 :(得分:2)

ServiceAreaSerializer序列化程序中,属性名称应为supplier而不是suppliers,因为在模型中的ServiceArea类中,属性为supplier,其中包含外键。模型和序列化程序中的字段必须匹配。