尝试POST创建商店时,我收到以下错误
尝试在序列化程序product
上获取字段StoreCategorySerializer
的值时, 得到了AttributeError。
序列化程序字段可能名称不正确,并且与ManyRelatedManager
实例上的任何属性或键都不匹配。
原始异常文本是:'ManyRelatedManager'对象没有属性'product'。
虽然我收到错误,但数据会保存到数据库中。
Serializers.py
class StoreCreateSerializer(ModelSerializer):
store_categories = StoreCategorySerializer()
merchant = UserSerializer()
class Meta:
model = Store
fields=("id",
"merchant",
"store_categories",
"name_of_legal_entity",
"pan_number",
"registered_office_address",
"name_of_store",
"store_contact_number",
"store_long",
"store_lat",
"store_start_time",
"store_end_time",
"store_off_day",
)
def create(self,validated_data):
store_categories_data = validated_data.pop('store_categories')
merchant_data = validated_data.pop('merchant')
for merchantKey, merchantVal in merchant_data.items():
try:
merchant,created = User.objects.get_or_create(username=merchantVal)
print('merchant',merchant)
validated_data['merchant']=merchant
store = Store.objects.create(**validated_data)
image = store_categories_data["product"].pop("image")
print('image pop results',image)
'''
image pop results OrderedDict([('image', <InMemoryUploadedFile: grocery.jpg (image/jpeg)>)])
'''
image_instance = ProductImage(**image)
print('image_instance',image_instance)
image_instance.save()
product = store_categories_data["product"]
product_instance = Product(
store=store,
image=image_instance,
name_of_product=product['name_of_product'],
description=product['description'],
price=product['price'],
active=product['active']
)
product_instance.save()
store_category = store_categories_data['store_category']
store_category = StoreCategory(product=product_instance, store_category=store_category)
store_category.product.store = store
store_category.save()
return store
except User.DoesNotExist:
raise NotFound('not found')
的 Models.py
class Store(models.Model):
merchant = models.ForeignKey(User)
name_of_legal_entity = models.CharField(max_length=250)
name_of_store = models.CharField(max_length=100)
store_off_day = MultiSelectField(choices=DAY, max_length=7, default='Sat')
store_categories = models.ManyToManyField('StoreCategory',blank=True)
class Product(models.Model):
store = models.ForeignKey(Store)
image = models.ForeignKey('ProductImage',blank=True,null=True)
name_of_product = models.CharField(max_length=120)
active = models.BooleanField(default=True)
class ProductImage(models.Model):
image = models.ImageField(upload_to='products/images/')
@property
def imageName(self):
return str(os.path.basename(self.image.name))
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)