在第三模型中创建两个模型之间的关系

时间:2019-06-16 04:51:02

标签: python django python-3.x

我是开发的新手,但步入僵局。 我正在尝试为Python3和Django创建一个资助系统

我有模特:

class Grant(models.Model):
    id = models.AutoField(primary_key=True)
    program = models.ForeignKey('Program',   on_delete=models.SET_NULL, null=True)
    title = models.CharField(max_length=200, help_text="Enter name of the grant")
    budget = models.DecimalField(max_digits=12, decimal_places=2,default=Decimal('0.00'),verbose_name="Total budget")
    grantee = models.ForeignKey('Grantee', on_delete=models.SET_NULL, null=True)
    description = models.TextField(max_length=1000)
    owner = models.ForeignKey(settings.AUTH_USER_MODEL,null=True, blank=True, on_delete=models.SET_NULL)

class Report(models.Model):
    title = models.CharField(max_length=100)
    grant_name = models.ForeignKey('Grant', on_delete=models.SET_NULL, null=True)
    CAT_LIST = (
    ('s', 'Salary'),
    ('e', 'Event'),
    ('t', 'Transportation'),
    ('p', 'Printing'),
    ('eq', 'Equipment'),
    ('of', 'Office'),
    ('o', 'Other')
    )
    categories = models.CharField(max_length=2, choices=CAT_LIST, blank=True)
    spent = models.DecimalField(max_digits=12, decimal_places=2,default=Decimal('0.00'))
    repbudget = models.DecimalField(max_digits=12, decimal_places=2,default=Decimal('0.00'),verbose_name="Budget")
    comment = models.TextField(max_length=300, null=True)
    # Below the mandatory fields for generic relation
    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey()

class Installment(models.Model):
    id = models.AutoField(primary_key=True)
    grant_name = models.ForeignKey('Grant', on_delete=models.SET_NULL, null=True)
    amount = models.DecimalField(max_digits=12, decimal_places=2,default=Decimal('0.00'))
    date = models.DateField(default=datetime.date.today)
    date_report = models.DateField(default=datetime.date.today)

现在,我需要为“分期付款”报告创建一个模型,该模型应包括同一“赠款”的“分期付款”和“报告”的类别。 像这样:

class InstallmentReport(models.Model):
    id = models.AutoField(primary_key=True)
    title =  models.ForeignKey('Report', on_delete=models.CASCADE)
    spent = models.DecimalField(max_digits=12, decimal_places=2,default=Decimal('0.00'))
    installment = models.ForeignKey('Installment', on_delete=models.CASCADE)

创建此报告时,我可以与Installment连接,但是无法想象如何过滤同一Grant的报告标题。 您能提供一些建议还是示例?

P.S。对于英语中的错误以及代码的设计,我深表歉意。

1 个答案:

答案 0 :(得分:0)

我认为我可以通过使用POST的视图模板来完成此操作,为此,我需要添加到Report的模型安装中。然后{% for categorie in installment.report %}。但是,如果我可以在创建或更新视图中做到这一点,那就可以了。但是我没有介绍如何过滤报告类别,没有它,用户应该从所有授予中的所有类别中进行选择,但这不是一个变体。

相关问题