Maxim Dunavicher
Maxim Dunavicher

Reputation: 635

How to access foreign key value in a django model?

I'm trying to build a simple Queue app, where a user can take a ticket with a number in a queue of a certain room.

I'm facing some problems defining the relationship between Ticket.number and Room.next_number_to_take. The value of Ticket.number on the tickets creation should be the Room.next_number_to_take however, I don't know how to define it in "Django" language without a specified init function for the class.

Here is my failed attempt (its failing on the save method of the ticket):

from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User


# Create your models here.
class Room(models.Model):
    name = models.CharField(max_length=100)
    room_master = models.ForeignKey(User, on_delete=models.CASCADE)
    current_visitor_number = models.BigIntegerField(default=0)
    next_number_to_take = models.BigIntegerField(default=0)

class Ticket(models.Model):
    request_date = models.DateTimeField(default=timezone.now)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    room = models.ForeignKey(Room, on_delete=models.CASCADE)
    number = models.BigIntegerField(default=0)

    def save(self, *args, **kwargs):
        self.number = self.room.next_number_to_take
        self.room.next_number_to_take += 1
        super(Ticket, self).save(*args, **kwargs)

I have previously tried the following which also failed:

class Ticket(models.Model):
    request_date = models.DateTimeField(default=timezone.now)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    room = models.ForeignKey(Room, on_delete=models.CASCADE)
    number = room.next_number_to_take
    room.next_number_to_take += 1

Upvotes: 0

Views: 713

Answers (1)

MiniGunnR
MiniGunnR

Reputation: 5800

I haven't tried this code myself. I think that when you change the next_number for the Room model, that model isn't saved. So I have added another line to it. See if it works and get back to me with the error if you have any.

def save(self, *args, **kwargs):
    self.number = self.room.next_number_to_take
    self.room.next_number_to_take += 1 # this line is ok but you need to save it
    self.room.save() # this is the new line to add
    super(Ticket, self).save(*args, **kwargs)

Upvotes: 1

Related Questions