我正在设计一个用于列出商店和创建商店的API。我可以列出商店,但在设计创建商店时我不会在商店序列化器中调用所有产品和商店类别序列化器而获得产品和商店类别字段。
我缩短的型号看起来像
class Merchant(models.Model):
user = models.ForeignKey(User)
phone = models.PositiveIntegerField(null=True,blank=True)
class Store(models.Model):
merchant = models.ForeignKey(Merchant)
name_of_legal_entity = models.CharField(max_length=250)
class Product(models.Model):
store = models.ForeignKey(Store)
image = models.ForeignKey('ProductImage',blank=True,null=True)
name_of_product = models.CharField(max_length=120)
class ProductImage(models.Model):
image = models.ImageField(upload_to='products/images/')
class StoreCategory(models.Model):
product = models.ForeignKey(Product,null=True, on_delete=models.CASCADE,related_name="store_category")
store_category = models.CharField(choices=STORE_CATEGORIES, default='GROCERY', max_length=10)
Serializer.py
class ProductImageSerializer(ModelSerializer):
class Meta:
model = ProductImage
fields = ( 'id','imageName', )
class ProductSerializers(ModelSerializer):
image = ProductImageSerializer(many=False,read_only=True)
class Meta:
model = Product
fields=('id','image','name_of_product','description','price','active',)
class StoreCategorySerializer(ModelSerializer):
product = ProductSerializers(read_only=True)
class Meta:
model = StoreCategory
class StoreSerializer(ModelSerializer):
# url = HyperlinkedIdentityField(view_name='stores_detail_api')
store_categories = StoreCategorySerializer(many=True)
merchant = MerchantSerializer(read_only=True)
class Meta:
model = Store
fields=("id",
"merchant",
"store_categories",
"name_of_legal_entity",
"pan_number",
"registered_office_address",
"name_of_store",
)
Views.py
class StoreCreateAPIView(CreateAPIView):
queryset = Store.objects.all()
serializer_class = StoreSerializer
parser_classes = (FormParser,MultiPartParser,)
def put(self, request, filename, format=None):
print('first put works')
file_obj = request.data['file']
print ('file_obj',file_obj)
return Response(status=204)
def perform_create(self, serializer):
print('then perform works')
serializer.save(user=self.request.user)
以下是它的外观截图
为什么它没有在表单中显示商家,产品和商店类别?
答案 0 :(得分:2)
从您要创建条目的序列化程序中删除read_only=True
。
像:
product = ProductSerializers(read_only=True)
应该是
product = ProductSerializers()
read_only
会阻止它被写入,因此我不会在结果中。