Django:模型关系和查询

时间:2019-04-27 07:34:04

标签: django model django-queryset

我已经多次进行模型关系测试,以使用户选择多个票证,这些票证将以 Ticket ID 的形式包含信息,并附带一个“订单ID” 。用户可以订购许多票证,每个票证ID都附带一个订购ID。当我在views.py中查询要创建的票证时,它表明未定义“ order_id”。如何查询,以便在创建票证信息时附加订单ID?您的建议会有所帮助!

models.py

class User(models.Model):
    first_name=models.CharField(max_length=100)
    last_name=models.CharField(max_length=100)
    email=models.CharField(max_length=100)
    password=models.CharField(max_length=100)
    created_at=models.DateTimeField(auto_now_add=True)
    updated_at=models.DateTimeField(auto_now=True)

class Order(models.Model):
    full_name=models.CharField(max_length=100)
    cc_number=models.PositiveIntegerField()
    exp_date=models.PositiveIntegerField()
    cvc=models.PositiveIntegerField()
    buyer=models.ForeignKey(User, related_name="bought_tickets", on_delete=models.PROTECT)
    created_at=models.DateTimeField(auto_now_add=True)
    updated_at=models.DateTimeField(auto_now=True)

class Ticket(models.Model):
    venue=models.CharField(max_length=100)
    quantity=models.PositiveIntegerField()
    price=models.DecimalField(default=25.00, max_digits=5, decimal_places=2, null=True, blank=True)
    loop=models.CharField(max_length=100)
    purchaser = models.ForeignKey(User, related_name="purchases", on_delete=models.PROTECT)
    order=models.ForeignKey(Order, related_name="orders", on_delete=models.PROTECT)
    created_at=models.DateTimeField(auto_now_add=True)
    updated_at=models.DateTimeField(auto_now=True)

views.py

def add(request):
    if not 'user_id' in request.session:
        return redirect('/chrisgrafil')
    if request.method!='POST':
        messages.error(request, 'Please select the following options')
        return redirect('/dashboard')
    else:
        Ticket.objects.create(venue=request.POST['venue'], quantity=request.POST['quantity'], loop=request.POST['loop'], purchaser=User.objects.get(id=request.session['user_id']), 

        order=Order.objects.get(id=['order_id']))

        return redirect ('/confirmation')

0 个答案:

没有答案