根据mod上的另一个字段自动填充Django外键

2024-09-29 22:35:29 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我现在有一个“Account”模型和“Account Comments”模型——请记住,我不能真正控制数据库的方案,我正在为现有的数据库编写一个包装器。在

在AccountComments模型下,有一个名为“Data”的字段。这就是AccountComments的实际位置,我试图基本上在Account模型上创建一个外键,而不需要重新设计并在Account上添加一个保存AccountID的“AccountComments”字段。在

class Account(models.Model):
    AccountID = models.AutoField(editable=False, db_column='AccountID', verbose_name='ID',
                             primary_key=True) 
    acctno = models.IntegerField(editable=True, unique=True, db_column='ACCTNO', verbose_name='Acct #', blank=True,
                             null=True)  # Field name made lowercase.
    accountComments = models.ForeignKey('accountComments',to_field='accountID',db_column='Data')

    def __str__(self):
        return str(self.acctno)

    class Meta:
        managed = False
        db_table = 'Account'


class accountComments(models.Model):
    accountCommentID = models.AutoField(db_column='AccountCommentID', primary_key=True)  # Field name made lowercase.
    accountID = models.IntegerField(db_column='AccountID')  # Field name made lowercase.
    EntryUserID = models.IntegerField(db_column='EntryUserID')  # Field name made lowercase.
    EntryStamp  = models.DateTimeField(db_column='EntryStamp', )  # Field name made lowercase.
    Data = models.TextField(db_column='Data')  # Field name made lowercase.
    guid = models.CharField(db_column='guid', max_length=255)  # Field name made lowercase.
    class Meta:
        managed = False
        db_table = 'AccountComment'

最后,希望accountComments在Account模型上使用“AccountID”来查找accountComments.accountID然后提供“数据”。在

我知道我可以用

^{pr2}$

但我希望它能与Django Admin一起工作,所以我需要它成为模型的一个集成部分。在

如果有人能给我指出正确的方向,谢谢。在


Tags: name模型truefielddbdatamodelscolumn
1条回答
网友
1楼 · 发布于 2024-09-29 22:35:29

你用外键做的太多了。在Django中跟随外键应该返回模型实例,而不是模型实例中的特定字段。在

{{cdg}应该存储在

accountComments = models.ForeignKey('accountComments',to_field='accountID',db_column='AccountID')

然后,要获得特定的account实例的Data,可以执行以下操作:

^{pr2}$

相关问题 更多 >

    热门问题