代码之家  ›  专栏  ›  技术社区  ›  Philip Mutua

在django中的模型中将同一外键作为不同字段使用两次[重复]

  •  1
  • Philip Mutua  · 技术社区  · 6 年前

    这个问题已经有了答案:

    我有一个模型 Transaction Type 已经 credit_account debit_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 回复  |  直到 6 年前
        1
  •  0
  •   Ken4scholars    6 年前

    这通常不是个坏主意,但你应该加上 related_name 因此Django可以在相关查询中区分它们

        2
  •  0
  •   Zoie    6 年前

    您需要为外键和gtg添加不同的相关名称。

    推荐文章