python - django 2外键从一个模型到另一个模型

标签 python django

有没有办法让模型中的 2 个外键与同一个模型相关。在示例中,我想将时间表中的“日期”和“主管”都作为 DateTimesheet 的外键。我想要完成的是让时间表与管理员中的 DateTimesheet 内联,并且能够一次输入日期和主管,然后内联输入多个时间表,而不必为每个时间表输入日期或主管。

class DateTimesheet(models.Model):
    date = models.DateField()
    supervisor = models.ForeignKey(User)
    class Meta:
        verbose_name = 'Daily Timesheet'
        unique_together = (('date', 'supervisor'),)

    def __unicode__(self):
        return '%s | %s' % self.date.strftime("%A, %B %d.")

class Timesheet(models.Model):
    date = models.ForeignKey(DateTimesheet)
    supervisor = models.ForeignKey(DateTimesheet)
    job = models.ForeignKey(Job)
    phase = models.ForeignKey(Phase)
    equip = models.ForeignKey(Equipment, null=True, blank=True)
    employee = models.ForeignKey(Employee)
    local = models.ForeignKey(Local)
    pay_class = models.ForeignKey(PayClass)
    reg = models.IntegerField(max_length=1)
    ot = models.IntegerField(max_length=2, null=True, blank=True)
    bill_rate = models.DecimalField(decimal_places=2,max_digits=6, blank=True,null=True)
    bill_hours = models.IntegerField(max_length=2,blank=True,null=True,)

最佳答案

如果您必须将一个模型上的外键指向同一模型,则必须 set fk_name on the corresponding inline admin :

class DateInline(admin.TabularInline):
    model = DateTimeSheet
    fk_name = "date"

关于python - django 2外键从一个模型到另一个模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4514415/

相关文章:

python - 创建一个倒序的优先级队列

python - 如何防止上传非图片

python - 在没有基于模型的数据库的情况下使用 Django View 和表单

python横截面曲线拟合

python - 当 AJAX 在 Django 中保存(并重新填充)我的表单时,为什么我会收到 '

java - 如果使用 ruby​​ on rails、python 或 java 可以做得更好,为什么还要使用 php 框架进行编程?

mysql - 限制 Django 中数据的生命周期

python - 更改/调整管理界面上的日期小部件

python - 如何让django runserver停止记录到pycharm中的控制台

python - 从单独的模型 Django 更新用户信息