Search code examples
python-3.xdjangodjango-modelsmodel

Django - Get Foreign key value directly with custom db_column


I'm trying to do what's described here: https://docs.djangoproject.com/en/dev/topics/db/optimization/#use-foreign-key-values-directly

I have a model like this:

class Pizza(models.Model):
    last_name = models.CharField(max_length=80, null=True, default=None)
    baker = models.OneToOneField(User, to_field='username', parent_link=True, null=True,
                                       db_column="django_username", default=None, db_constraint=False)

I have a pizza instance, I want the actual username stored in the Pizza table without hitting the user table.


Solution

  • You can always access the actual value of a ForeignKey or OneToOneField column by appending "_id" to the field name

    pizza.baker_id