简体   繁体   中英

Django Foreign Key automatically filled based off of another field on model

So I currently have an "Account" Model and "Account Comments" Model -- keep in mind, that I can't really control the scheme of the database, and I'm writing a wrapper around existing DB.

Under the AccountComments Model, there is a field called "Data". It is where the AccountComments actually are and I'm trying to basically create a foreign key on the Account model without actually having to redesign and add a "AccountComments" field on Account that holds the AccountID.

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'

ultimately, want accountComments on the Account Model to use 'AccountID' to do a lookup onto accountComments.accountID and then provide back 'Data'.

I know that I can use

def accountComments(self):
    return str(accountComment.objects.get(accountID = self.AccountID).Data)

but I want it to work with Django Admin, so I need it to be an integrated part of the model.

Thanks if anyone can point me in the right direction.

You're trying to do too much with a foreign key. Following a foreign key in Django should return the model instance, not a particular field from the model instance.

The db_column should be the column in the Account table that stores the id, eg

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

Then, to get the Data for a particular account instance, you would do:

account.accountComments.Data

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM