我希望使用ServiceArea django rest框架来创建新的实例,但不知道如何在CreateApiView中设置supplier foreignKey字段。我试图使用PrimaryKeyRelatedField来实现它,但是当我将queryset属性设置为Supplier.objects.all()时,它会给出错误'ServiceArea' object has no attribute 'suppliers'。我怎样才能在CreateApiView中访问CreateApiView?我的代码:
models.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.titleserializers.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',
]views.py
class ServiceAreaListApiView(ListAPIView, CreateAPIView):
queryset = ServiceArea.objects.all()
serializer_class = ServiceAreaSerializer发布于 2018-04-24 14:01:40
在ServiceAreaSerializer序列化程序中,属性名应该是supplier,而不是suppliers,因为在模型中的ServiceArea类中,属性是包含外键的supplier。模型和序列化程序中的字段必须匹配。
https://stackoverflow.com/questions/50003227
复制相似问题