Home > Mobile >  Create a lookup in django
Create a lookup in django

Time:11-05

I Have an accounts table with account number and account name in a model called accounts

how do I create a lookup such that whenever I enter an account number in django template, account name get populated automatically

my models at attempt are

class Account(models.Model):
    account_number = models.IntegerField()
    account_name = models.CharField(max_length=50)
    bank_name = models.ForeignKey(Bank, on_delete=models.CASCADE)
    status = models.CharField(max_length=50)

    def __str__(self):
        return account_name

    def get_absolute_url(self):
        return reverse_lazy('accounts')


class AccountLookup(models.Model):
    account_number = models.ForeignKey(Account, on_delete=models.CASCADE):
    account_name = models. ???????????

CodePudding user response:

If you want something you can use in a template that will render account name starting from an AccountLookup object, then its

{{accountlookup_instance.account_number.account_name}}

Note that this will hit the DB again, unless you used select_related() on the queryset which obtained the AccountLookup object(s) in the first place.

Python code can likewise use this dotted path, with the same caveat.

You might regard it as a simplification to be able to refer to what looks like a field (but isn't). In which case you define it as a property

class AccountLookup(models.Model):
    account_number = models.ForeignKey(Account, on_delete=models.CASCADE)
    ...
    @property
    def account_name(self):
        return self.account_number.account_name

(It gets more useful if you need to apply some standard formatting to the account name to convert it into a more human-readable form in this context).

By the way, calling it account_number is confusing. Better to just name a ForeignKey field for what it is. account in this case: the account object linked by a ForeignKey to this object. Yes, it's represented internally by an account_id which is commonly an integer (the auto-generated primary key), but that's a low level detail Django programmers are not often concerned with.

  • Related