如何在Django DB中存储多个模型对象

时间:2019-03-16 09:31:32

标签: python django

我想将多个产品列表存储到买方模型中。我该怎么做? 我收到此错误,提示无法分配查询集。:

ValueError at /shop/items/buy/now/
Cannot assign "<QuerySet [<Product: applewatch>, <Product: laptop4>]>":
"Buyer.product" must be a "Product" instance.   
  

models.py

class Product(models.Model):
    name = models.CharField(max_length=250)
    image = models.ImageField(upload_to='products')
    seller = models.ForeignKey(User,on_delete=CASCADE)
    slug = AutoSlugField(populate_from='name')
    category = models.ForeignKey(Category,on_delete=CASCADE)
    description = models.TextField(blank=True,default="Description Field")
    brand = models.CharField(max_length=250)
    quantity = models.PositiveIntegerField(default=1)
    price = models.DecimalField(max_digits=10,default=0.0,decimal_places=2)
    shipping_fee = models.DecimalField(max_digits=10,default=0.0,decimal_places=2)
    featured = models.BooleanField(default=False)
    active = models.BooleanField(default=True)
    created = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.name


class Buyer(models.Model):
    full_name = models.CharField(max_length=250)
    phone = models.CharField(max_length=20)
    city = models.CharField(max_length=250,choices=city_choices)
    address = models.CharField(max_length=250,default="123Area , House#123 , Street#123")
    product = models.ForeignKey(Product,on_delete=CASCADE)

    def __str__(self):
        return self.full_name
  

forms.py

class BuyerDeliveryForm(forms.ModelForm):
class Meta:
    model = Buyer
    fields = ['full_name','phone','city','address']
  

views.py

def items_buy_now(request):
    if not request.user.is_authenticated:
        messages.info(request, 'You have to logged in first.')
        return redirect('%s?next=%s' % (settings.LOGIN_URL, request.path))
    sess = request.session.get("data", {"items": []})
    if request.method == "POST":
        form = BuyerDeliveryForm(request.POST)
        if form.is_valid():
            buyer = form.save(commit=False)
            buyer.product = Product.objects.filter(active=True, slug__in=sess["items"])
            buyer.save()
            return redirect('shop:payment')
    else:
        form = BuyerDeliveryForm()
    return render(request, 'shop/delivery_form.html', {'form': form})

def mycart(request):
    sess = request.session.get("data", {"items": []})
    products = Product.objects.filter(active=True, slug__in=sess["items"])
    if not products:
        return render(request,'shop/empty_cart.html')
    context = {"products": products,
               "categories": categories}
    return render(request,'shop/cart_item.html',context)
  

urls.py

path('mycart/', views.mycart, name='mycart'),
path('items/buy/now/', views.items_buy_now, name='items_buy_now'),
  

admins.py

admin.site.register(Product)



class BuyerAdmin(admin.ModelAdmin):
    readonly_fields = ['product']

admin.site.register(Buyer,BuyerAdmin)

1 个答案:

答案 0 :(得分:0)

在这样的By = uyer模型中,您必须使用多对多关系而不是ForeignKey

class Buyer(models.Model):
    full_name = models.CharField(max_length=250)
    phone = models.CharField(max_length=20)
    city = models.CharField(max_length=250,choices=city_choices)
    address = models.CharField(max_length=250,default="123Area , House#123 , Street#123")
    product = models.ManyToManyField(Product,on_delete=CASCADE)

    def __str__(self):
        return self.full_name

然后在views.py

中为该字段分配值
        if form.is_valid():
            buyer = form.save(commit=False)
            buyer.save()
            buyer.product.set(Product.objects.filter(active=True, slug__in=sess["items"]))
            return redirect('shop:payment')