Django: Models relationship and queries

Asked by At

I been testing with model relationships several times for a User to select a number of ticket/s that will contain the information in the form of Ticket ID, and along with it, comes an Order ID that I will use after when the user input their CC information with it. A user can order many ticket/s and each Ticket ID has an Order ID attached with it. When I query for the Ticket to be created in my views.py--it shows that "order_id" is not defined. How do I query so that when I create the ticket information, an order ID attaches with it? Your suggestions would be helpful!

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 Answers