创建具有嵌套orderDict的对象

时间:2016-08-03 01:10:15

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

我的store_categories_data有一个嵌套的orderDict,如下所示

store_categories_data 
OrderedDict([('product', OrderedDict([('image', OrderedDict([('image', <InMemoryUploadedFile: bag.jpg (image/jpeg)>)])), 
('name_of_product', 'Ladies Pink Bag'), ('description', 'description'), ('price', Decimal('1600')), ('active', True)])), 
('store_category', 'BAGS')])

我想传递所有产品信息,如图片,名称,描述等。但是有3个orderDict。 如何将值传递给get_or_create()以创建store_categories对象?

我的代码

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)
                print('__________________________________')
                image = store_categories_data["product"].pop("image")
                image_instance = ProductImage(**image)
                print('image_instance',image_instance)
                product = store_categories_data["product"]
                print('product creation returns',product['name_of_product'])
                product_instance = Product(
                                            image=image_instance,
                                            name_of_product=product['name_of_product'],
                                            description=product['description'],
                                            price=product['price'],
                                            active=product['active']
                                        )
                print('product_instance',product_instance)
                store_category = store_categories_data['store_category']
                print('store_category',store_category)
                store_category = StoreCategory(product=product_instance, store_category=store_category)
                print('store category instance',store_category)
                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)
    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)

1 个答案:

答案 0 :(得分:0)

假设OrderedDict中的嵌套映射到关系数据库中的外键关系,您只需要从内到外按顺序显式创建所有3条记录。像下面这样的东西应该足以在剩下的时间里进行。

注意:将带有**的关键字参数解包的解包仅适用于较新版本的python&gt; = Python3.5

image = store_categories_data["product"].pop("image")
image_instance = Image(**image)
product = store_categories_data["product"]
product_instance = Product(image=image_instance, product=product)
store_category = store_categories_data['store_category']
store_category = StoreCategory(product=product_instance, store_category=store_category)