社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Django

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

Philip Mutua • 4 年前 • 269 次点击  

这个问题已经有了答案:

我有一个模型 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)()
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/50577
 
269 次点击  
文章 [ 2 ]  |  最新文章 4 年前
Zoie
Reply   •   1 楼
Zoie    5 年前

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

Ken4scholars
Reply   •   2 楼
Ken4scholars    5 年前

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