我可以多次使用同一个外键吗?

时间:2019-01-21 09:10:18

标签: django-models

我有一个客户表和一个事件表。客户端是事件表中的FK。用户可以选择特定日期的客户。我希望我的事件表具有星期日,星期一,...,星期六的字段,因此用户只需要从下拉列表中选择一个客户端即可。

我已经尝试过这样设置我的模型,但是在尝试迁移时它不起作用:

class Client(models.Model):
    name = models.CharField(max_length=50)

class Event(models.Model):
    week = models.DateField(blank=False)
    sunday = models.ForeignKey(Client, on_delete=models.CASCADE)
    monday = models.ForeignKey(Client, on_delete=models.CASCADE)
    tuesday = models.ForeignKey(Client, on_delete=models.CASCADE)
    wednesday = models.ForeignKey(Client, on_delete=models.CASCADE)
    thursday = models.ForeignKey(Client, on_delete=models.CASCADE)
    friday= models.ForeignKey(Client, on_delete=models.CASCADE)
    saturday = models.ForeignKey(Client, on_delete=models.CASCADE)

我知道这种允许选择的方式:

position = models.CharField(max_length=20, choices=POS_CHOICES)

但是我想使用表“ client”中的选择,而不是对选择进行硬编码。

1 个答案:

答案 0 :(得分:0)

仅需使用“ related_name”:

class Event(models.Model):
week = models.DateField(blank=False)
sunday = models.ForeignKey(Client, on_delete=models.CASCADE, related_name='sunday', null=True)
monday = models.ForeignKey(Client, on_delete=models.CASCADE, related_name='monday', default=0)
tuesday = models.ForeignKey(Client, on_delete=models.CASCADE, related_name='tuesday', default=0)
wednesday = models.ForeignKey(Client, on_delete=models.CASCADE, related_name='wednesday', default=0)
thursday = models.ForeignKey(Client, on_delete=models.CASCADE, related_name='thursday', default=0)
friday = models.ForeignKey(Client, on_delete=models.CASCADE, related_name='friday', default=0)
saturday = models.ForeignKey(Client, on_delete=models.CASCADE, related_name='saturday', null=True)