Python django rest_框架在CreateAPIView中选择foreignKey模型
我想使用django rest framework创建新的Python django rest_框架在CreateAPIView中选择foreignKey模型,python,django,django-rest-framework,Python,Django,Django Rest Framework,我想使用django rest framework创建新的ServiceArea实例,但不知道如何在CreateApiView中设置supplierforeignKey字段。我试图使用PrimaryKeyRelatedField来执行此操作,但当我将queryset属性设置为等于Supplier.objects.all()时,它会给出错误“ServiceArea”对象没有属性“suppliers”。如何在CreateApiView中访问供应商?我的代码: models.py class Supp
ServiceArea
实例,但不知道如何在CreateApiView
中设置supplier
foreignKey字段。我试图使用PrimaryKeyRelatedField
来执行此操作,但当我将queryset
属性设置为等于Supplier.objects.all()
时,它会给出错误“ServiceArea”对象没有属性“suppliers”
。如何在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.title
序列化程序.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
在
serviceaserializer
serializer中,属性名称应该是supplier
,而不是suppliers
,因为在模型的serviceare
类中,属性是supplier
,其中包含外键。模型和序列化程序中的字段必须匹配。在serviceaserializer
序列化程序中,属性名称应该是supplier
,而不是suppliers
,因为在模型的serviceare
类中,属性是包含外键的supplier
。model和serializer中的字段必须匹配。您打算在ServiceArea model的“supplier”属性中使用null=True
什么?@RaghavMittal我忘了删除它。用于为迁移提供默认值,因为在开发时不希望删除现有服务区域。您打算在服务区域模型的“供应商”属性中使用null=True
?@raghamittal我忘了删除它。用于为迁移提供默认值,因为在开发时不想删除现有服务区域。错误:“Supplier”对象不可移植。
我解决了我的问题。在ServiceAreaSerializer
中,我只需在类Meta
中添加以下行:字段='\uuuuuuuuuuuuu'
,然后在CreateApiView中为servicearea
实例选择供应商。@MaximZemskov-Nice。我希望我能帮上忙。错误:'Supplier'对象不可编辑。
我解决了我的问题。在ServiceAreaSerializer
中,我只需在类Meta
中添加以下行:字段='\uuuuuuuuuuuuu'
,然后在CreateApiView中为servicearea
实例选择供应商。@MaximZemskov-Nice。我希望我能帮上忙。