在Django模型中保存多对多对象?

时间:2018-10-08 06:40:42

标签: python django

我仍在学习使用Django,因此我对某些内容不清楚。

我有一个产品模型和类别模型。一个产品可以位于多个类别中,并且多个类别可以具有相同的产品。

因此,这是多对多的关系。现在,我想允许用户从html中选择多个类别,然后保存类别并将其链接到产品模型中的类别对象。我对此完全迷失了。

一种方法是使用Modelform,但我不想那样做。我还有其他方法可以做到这一点吗?

models.py:

class Category(models.Model):
    name = models.CharField(max_length=50)
    slug = models.SlugField(max_length=50, unique=True,
                            help_text='Unique value for product page URL, created from name.')
    description = models.TextField()
    is_active = models.BooleanField(default=True)
    meta_keywords = models.CharField("Meta Keywords", max_length=255,
                                        help_text='Comma-delimited set of SEO keywords for meta tag')
    meta_description = models.CharField("Meta Description", max_length=255,
                                        help_text='Content for description meta tag')
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse('catalog:categories', kwargs={'category_slug': self.slug})

    class Meta:
        ordering = ['-created_at']
        verbose_name_plural = 'Categories'


class Product(models.Model):
    name = models.CharField(max_length=255, unique=True)
    slug = models.SlugField(max_length=255, unique=True,
                            help_text='Unique value for product page URL, created from name.')
    brand = models.CharField(max_length=50)
    sku = models.CharField(max_length=50)
    price = models.DecimalField(max_digits=9, decimal_places=2)
    old_price = models.DecimalField(max_digits=9, decimal_places=2, blank=True, default=0.00)
    thumbnail = models.FileField(upload_to='static/images/products/thumbnails')
    imageurls = models.CharField(max_length=1000)
    is_active = models.BooleanField(default=True)
    is_bestseller = models.BooleanField(default=False)
    is_featured = models.BooleanField(default=False)
    quantity = models.IntegerField()
    description = models.TextField()
    meta_keywords = models.CharField(max_length=255, help_text='Comma-delimited set of SEO keywords for meta tag')
    meta_description = models.CharField(max_length=255, help_text='Content for description meta tag')
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    categories = models.ManyToManyField(Category)

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse('catalog:products', kwargs={'product_slug': self.slug})

    def sale_price(self):
        if self.old_price > self.price:
            return self.price
        else:
            return None

    class Meta:
        ordering = ['-created_at']

部分views.py:

if request.method =='POST':
    print ('entered')
    name = request.POST['name']
    brand = request.POST['brand']
    sku = request.POST['sku']
    price = request.POST['price']
    quantity = request.POST['quantity']
    description = request.POST['description']
    imageurls = request.POST['urls']

    print('imageurls',imageurls)

    categorylist = request.POST['categories']
    print('categorylist',categorylist)
    categories =  re.findall(r"[\w']+", categorylist)
    print categories

    imageurls = imageurls.split('~')
    print('iageurls',imageurls)

    for x in categories:
        categoryobj = Category.objects.filter(name=x).values()

        print ('categoryobj',categoryobj)
        # Product.objects.create(name=name,sku=sku,brand=brand,price=price,quantity=quantity,description=description,imageurls=imageurls,categories=categoryobj)
return HttpResponse('success')

尝试保存以上方法会给我错误。

1 个答案:

答案 0 :(得分:0)

product=Product.objects.create(name=name,sku=sku,brand=brand,price=price,quantity=quantity,description=description,imageurls=imageurls)

category_queryset = []    
for x in categories:
    category = Category.objects.filter(name=x).first()
    category_queryset.append(category)

product.categories.set(category_queryset)