无法分配查询集,必须是实例

时间:2019-03-16 07:11:46

标签: python django

我收到此值错误:

  

ValueError在/ shop / items / buy / now /   无法分配“ QuerySet产品:mcloth2,产品:手表,产品:手表”:
“ Buyer.product”必须是“ Product”实例。
  请求方法:POST   要求网址:http://127.0.0.1:8004/shop/items/buy/now/   Django版本:2.1.5   异常类型:ValueError   异常值:
  无法分配“,,]>”:“ Buyer.product”必须是“ Product”实例。

buyer.product =产品

  

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": []})
    product = Product.objects.filter(active=True, slug__in=sess["items"])
    if request.method == "POST":
        form = BuyerDeliveryForm(request.POST)
        if form.is_valid():
            buyer = form.save(commit=False)
            buyer.product = product
            buyer.save()
            return redirect('shop:payment')
    else:
        form = BuyerDeliveryForm()
    return render(request, 'shop/delivery_form.html', {'form': form})



def cart(request,slug):
    product = Product.objects.get(slug=slug)
    initial = {"items":[],"price":0.0,"count":0}
    session = request.session.get('data',initial)
    if slug in session['items']:
        messages.error(request,'Already added.')
    else:
        session["items"].append(slug)
        session["price"] += float(product.price)
        if product.shipping_fee:
            session['price'] += float(product.shipping_fee)
        session["count"] += 1
        request.session["data"] = session
        messages.success(request,'Added to Cart.')
    return redirect('shop:detail',slug)


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)
  

models.py

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




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
  

forms.py

    class SellProductForm(forms.ModelForm):
    class Meta:
        model = Product
        fields = ['name','image','category', 'description', 'brand', 'quantity', 'price', 'shipping_fee']


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

urls.py`

  path('items/buy/now/',views.items_buy_now,name='items_buy_now'),
  path('mycart/', views.mycart, name='mycart'),
  path('<slug>/cart/', views.cart, name='cart'),

`

  

模板

 {% extends "shop/base.html" %}
{% load bootstrap4 %}
<title>{% block title %}Cart Items{% endblock  %}</title>

{% block content %}
<center>
  {% bootstrap_messages %}
        {% for item in products %}
       <div class="col-lg-4 col-md-4 mb-4">
              <div class="card h-50">
                <div class="card-body">
                    <a href="{% url 'shop:detail' item.slug %}"><img src="/media/{{ item.image }}" width=200 height="100" alt=""></a>
                    <div class="card-body">
                      <h4 class="card-title">
                        <a href="{% url 'shop:detail' item.slug %}">{{ item.name|title }}</a>
                      </h4>
                      <h5>Rs. {{ item.price|floatformat:"2" }}</h5>
                        <h5>Shipping fee:{{item.shipping_fee}}</h5>
                    </div>
                    </div>
                  </div>
                </div>
     {% endfor %}
          <b>Items({{request.session.data.items|length}})</b><br>
              {% for item in products %}
             {{item.name}}: Rs.{{item.price}}
              <br>
              {% endfor %}
          <br>
              <h5>Shipping Fee:</h5>
             {% for item in products %}
              {{item.name}}: Rs{{item.shipping_fee }} <br>
              {% endfor %}
              <br>
              <h5>Total Price:<b style="color:blue;">Rs
              {{request.session.data.price}}</b></h5>
               <a class="btn btn-success" href="{% url 'shop:items_buy_now' %}">PROCEED TO CHECKOUT</a>



              <br><br>

      </div>



    </center>
{% endblock %}

2 个答案:

答案 0 :(得分:1)

基本上,Django的ORM期望对象不仅仅是键或查询集。

注意:必须先保存对象,然后才能将其分配给外键关系

尝试

在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": []})
    product = Product.objects.filter(active=True, slug__in=sess["items"])
    if request.method == "POST":
        form = BuyerDeliveryForm(request.POST)
        if form.is_valid():
            buyer = form.save(commit=False)
            buyer.product = Product.objects.get(active=True, slug=sess["items"])
            buyer.save()
            return redirect('shop:payment')
    else:
        form = BuyerDeliveryForm()
    return render(request, 'shop/delivery_form.html', {'form': form})

有关更多详细信息,请参见this

答案 1 :(得分:1)

  1. 过滤器返回多个对象,您必须选择一个。

    product = Product.objects.filter(active=True, slug__in=sess["items"])
    if request.method == "POST":
       buyer.product = product.first()
    
  2. 在这种情况下,您可以使用get方法。

    product = Product.objects.get(active=True, slug__in=sess["items"])
    

更多Difference between Django's filter() and get() methods