【问题标题】:error while getting foreignkey id in django在 django 中获取外键 ID 时出错
【发布时间】:2021-10-02 10:59:18
【问题描述】:

我是 django 的新手。我正在尝试使用 django 制作发票生成器应用程序。员工输入客户 ID 并将其带到发票页面。在发票页面中,员工可以输入产品 ID,产品和客户信息将添加到发票模型对象中。所以我想为相同的发票 id 或想要按客户 id 过滤,这将获得客户 id 的所有发票这里是代码 models.py

from django.db import models
from account.models import Customer
from product.models import Product

class Invoice(models.Model):
    products = models.ForeignKey(Product, on_delete=models.CASCADE, default=1)
    customers = models.ForeignKey(Customer, on_delete=models.CASCADE, default=4)
    date = models.DateTimeField(auto_now_add=True)
    total = models.BigIntegerField(default=0)
    quantity = models.IntegerField(default=0)

views.py

def billingform(request):
if request.method == "POST":
    cid = request.POST["customerId"]
    customer = Customer.objects.get(id=cid)
    request.session['customerId'] = cid
    return redirect('invoice')
return render(request, 'bform.html')
def invoice(request):
    cid = request.session.get('customerId')
    customer = Customer.objects.get(id=cid)
    if request.method == "POST":
        pd = request.POST["product_id"]
        qt = int(request.POST["quantity"])
        product = Product.objects.get(id=pd)
        pd_price = int(product.selling_price)
        total = pd_price*qt
        pd_name = product.name
        Invoice.objects.create(products = product,
                                    quantity = qt, total=total, customers = customer)
        cust_id = Invoice.objects.get(id, customers=customer.id)
        product_name = cust_id.products
        product_quantity = cust_id.quantity
        product_total = cust_id.total
        return render(request, 'invoice.html', { "total":product_total, "customer": customer, 
                     "product_names": product_name,
                     "quantitys": product_quantity,})
    else:
        return render(request, 'invoice.html', {"customers": customer})

显示错误 TypeError: cannot unpack non-iterable builtin_function_or_method object

【问题讨论】:

  • 请使用堆栈跟踪更新问题。

标签: django django-models django-views django-templates


【解决方案1】:
cust_id = Invoice.objects.get(id=customer.id)

Get:获取单个对象并将其分配给变量。所以这应该纠正你的错误

【讨论】:

    【解决方案2】:

    可能是这一行的错误..

    cust_id = Invoice.objects.get(id, customers=customer.id)
    

    换成

    cust_id = Invoice.objects.get(id=customer.id, customers=customer.id)
    

    如果它不起作用,请告诉我你的模板文件也显示给我..

    【讨论】:

      猜你喜欢
      • 2020-07-15
      • 2018-12-16
      • 1970-01-01
      • 2021-01-13
      • 2020-03-14
      • 1970-01-01
      • 1970-01-01
      • 2017-10-03
      • 1970-01-01
      相关资源
      最近更新 更多