无法将产品对象保存到数据库

时间:2016-08-04 12:35:29

标签: python django python-3.x django-rest-framework django-1.9

我在尝试发布商店,产品,类别和商家数据时收到错误消息。 / api / stores / create /的错误是 ValueError 禁止使用save()来防止因未保存的相关对象“产品”而导致数据丢失。

代码

class Store(models.Model):
    merchant = models.ForeignKey(User)
    name_of_legal_entity = models.CharField(max_length=250)
    pan_number = models.CharField(max_length=20)
    registered_office_address = models.CharField(max_length=200)
    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)
    description = models.TextField(blank=True, null=True)
    price = models.DecimalField(decimal_places=2, max_digits=20)
    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)

Serializers.py

class ProductSerializers(ModelSerializer):
    image = ProductImageSerializer()
    class Meta:
        model = Product
        fields=('id','image','name_of_product','description','price','active',)

class StoreCategorySerializer(ModelSerializer):
    product = ProductSerializers()
    class Meta:
        model = StoreCategory

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)
                print(type(merchant))
                validated_data['merchant']=merchant
                store = Store.objects.create(**validated_data)
                image = store_categories_data["product"].pop("image")
                image_instance = ProductImage(**image)
                product = store_categories_data["product"]
                product_instance = Product(
                                            image=image_instance,
                                            name_of_product=product['name_of_product'],
                                            description=product['description'],
                                            price=product['price'],
                                            active=product['active']
                                        )
                store_category = store_categories_data['store_category']
                print('store_category',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')

1 个答案:

答案 0 :(得分:0)

使用object.save(commit = False)的东西。 https://docs.djangoproject.com/en/1.9/topics/forms/modelforms/#the-save-method此文档将对此有所帮助。