我想使用 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',
]
答案 0 :(得分:2)
在ServiceAreaSerializer
序列化程序中,属性名称应为supplier
而不是suppliers
,因为在模型中的ServiceArea
类中,属性为supplier
,其中包含外键。模型和序列化程序中的字段必须匹配。