在Django的模型中两次将相同的外键用作不同的字段

时间:2018-12-06 12:06:30

标签: django python-3.x django-rest-framework

我有一个模型Transaction Type,其中有credit_accountdebit_account字段。这两个字段都是来自Account模型的外键。让它们像我下面实现的方式一样好吗?

class TransactionType(models.Model):
    name = models.CharField(max_length=255)
    organization = models.IntegerField(null=False, blank=False)  
    credit_account = models.ForeignKey(Account)
    debit_account = models.ForeignKey(Account)

帐户模型

class Account(MPTTModel):

    TYPES = Choices(
        ("AS", "asset", "Asset"),  # Eg. Cash in bank
        ("LI", "liability", "Liability"),  # Eg. Loans, bills paid after the fact (in arrears)
        ("IN", "income", "Income"),  # Eg. Sales, housemate contributions
        ("EX", "expense", "Expense"),  # Eg. Office supplies, paying bills
        ("EQ", "equity", "Equity"),  # Eg. Money from shares
        ("TR", "trading", "Currency Trading"),  # Used to represent currency conversions
        ("OR", "operating_revenues", "Operating Revenues"),
        ("OX", "operating_expenses", "Operating Expenses"),
        ("NR", "nonoperating_revenues", "Non-Operating Revenues"),
        ("NX", "nonoperating_expenses", "Non-Operating Expenses"),
    )


    uuid = SmallUUIDField(default=uuid_default(), editable=False)
    name = models.CharField(max_length=255,blank=True, null=True)
    parent = TreeForeignKey(
        "self",
        null=True,
        blank=True,
        related_name="children",
        db_index=True,
        on_delete=models.CASCADE,
    )
    code = models.CharField(max_length=3, null=True, blank=True)
    full_code = models.CharField(max_length=100, db_index=True, unique=True, null=True, blank=True)
    account_type = models.CharField(max_length=255,choices=TYPES, blank=True)
    # is_bank_account = models.BooleanField(default=False, blank=True,)
    currencies = ArrayField(models.CharField(max_length=255, db_index=True))
    organization = models.IntegerField(null=False, blank=False)

    objects = AccountManager.from_queryset(AccountQuerySet)()

2 个答案:

答案 0 :(得分:0)

通常这不是一个坏主意,但是您应该添加一个related_name,以便Django可以在相关查询中对它们进行区分

答案 1 :(得分:0)

您将需要为两个外键添加不同的相关名称,并且您是gtg。