我正在尝试在django中创建两个模型Reservation和DetailsReservation,我需要这些模型具有相同的userReservation。例如,如果我创建一个ID为1和User:4的Reservation时,创建带有Reservation 1的Details时在userbyReserva中复制用户
class Reservation(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
userReservation = models.ForeignKey(User, on_delete=models.CASCADE, default=1)
class DetailsReservation(models.Model):
Reservation = models.ForeignKey(Reservation, blank=False, on_delete=models.CASCADE, null=True)
userbyReserva = #same user that do reservate
答案 0 :(得分:0)
您可以使用方法作为属性通过Reservation
访问用户。这是最简单的方法。
有关代码的一些注释:
default=1
。如果未设置该关系,则最好引发一个错误。 (如果删除User = 1会怎样?)DetailReservation
对象相关时,用户才可用;如果未设置保留,detail_reservation.user
将返回None。reservation
中可选的DetailReservation
关系。看看
class Reservation(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
user = models.ForeignKey(User, on_delete=models.CASCADE, )
class DetailReservation(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
reservation = models.ForeignKey(Reservation, blank=False, related_name='details',
on_delete=models.CASCADE, null=True)
@property
def user(self):
return reservation.user if reservation else return None