如何在django模型中访问外键值?

时间:2018-02-02 17:04:37

标签: python django django-models

我正在尝试构建一个简单的Queue应用程序,用户可以在某个房间的队列中获取带有号码的票证。

我在定义Ticket.number和Room.next_number_to_take之间的关系时遇到了一些问题。 Ticket.number在创建故障单时的值应该是Room.next_number_to_take但是,我不知道如何在没有为该类指定的 init 函数的情况下用“Django”语言定义它。

这是我失败的尝试(它在故障单的保存方法上失败):

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)

我之前尝试了以下也失败了:

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

1 个答案:

答案 0 :(得分:1)

我自己没有试过这段代码。我认为当您更改next_number模型的Room时,该模型不会被保存。所以我添加了另一行。看看它是否有效,如果你有任何错误,请回复我。

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)