119

Is there a way to set foreign key relationship using the integer id of a model? This would be for optimization purposes.

For example, suppose I have an Employee model:

class Employee(models.Model):
  first_name = models.CharField(max_length=100)
  last_name = models.CharField(max_length=100)
  type = models.ForeignKey('EmployeeType')

and

EmployeeType(models.Model):
  type = models.CharField(max_length=100)

I want the flexibility of having unlimited employee types, but in the deployed application there will likely be only a single type so I'm wondering if there is a way to hardcode the id and set the relationship this way. This way I can avoid a db call to get the EmployeeType object first.

User
  • 62,498
  • 72
  • 186
  • 247

3 Answers3

239

Yep:

employee = Employee(first_name="Name", last_name="Name")
employee.type_id = 4
employee.save()

ForeignKey fields store their value in an attribute with _id at the end, which you can access directly to avoid visiting the database.

The _id version of a ForeignKey is a particularly useful aspect of Django, one that everyone should know and use from time to time when appropriate.

caveat: [ < Django 2.1 ]

@RuneKaagaard points out that employee.type is not accurate afterwards in recent Django versions, even after calling employee.save() (it holds its old value). Using it would of course defeat the purpose of the above optimisation, but I would prefer an accidental extra query to being incorrect. So be careful, only use this when you are finished working on your instance (eg employee).

Note: As @humcat points out below, the bug is fixed in Django 2.1

sm7
  • 53
  • 8
Will Hardy
  • 14,588
  • 5
  • 44
  • 43
  • [model `.save()`](https://github.com/django/django/blob/731f313d604a6cc141f36d8a1ba9a75790c70154/django/db/models/base.py#L708) uses the field `attname` ([`pre_save()` returns the `attname` value](https://github.com/django/django/blob/master/django/db/models/fields/__init__.py#L602)). For ForeignKeys, `attname` is the name with `_id` suffix. Also, the `foobar_id` attribute of a model instance is [automatically updated](https://github.com/django/django/blob/master/django/db/models/fields/related.py#L467) when you set `foobar`. But where is it officially documented? – Denilson Sá Maia Sep 04 '14 at 14:36
  • 9
    Using foreign key values directly: https://docs.djangoproject.com/en/1.8/topics/db/optimization/#use-foreign-key-values-directly – Dan Oliphant Jun 11 '15 at 19:24
  • 1
    I tested this on Django 1.7 today, and it's not a good idea there. While it works, and the `type` field gets written to the database, if you access the `type` property afterwards it doesn't reflect the change. Said in code, this would fail `assert(employe.type.id == 4)`. – Rune Kaagaard Jan 09 '17 at 20:29
  • @RuneKaagaard Wow, I didn't expect that. I expected Django to perform an SQL query when accessing the attribute and returning the relevant `Type` instance. But it didn't, it returned the value from when the `Employee` instance was created. I this this is a bug in Django, I would prefer inefficient to incorrect, I'll report it. – Will Hardy Jan 09 '17 at 20:46
  • 1
    @WillHardy Exactly, got bitten by that today, when logging a change in a FK field. I thinks Django means the `_id` shortcut to be readonly, and at least it should be documented as such. – Rune Kaagaard Jan 09 '17 at 20:50
  • my workaround to the problem @RuneKaagaard mentioned is to also invalidate the cached value of the related object. This is quite ugly because it touches the innards of the Django Model, but it works: `if hasattr(employee, '_type_cache'): delattr(employee, '_type_cache')` – Amichai Schreiber Nov 19 '17 at 14:38
  • 3
    @AmichaiSchreiber I believe the next release of Django will have a fix for this problem: https://code.djangoproject.com/ticket/27710 – Will Hardy Dec 03 '17 at 01:26
  • 6
    For anyone coming here in the future, this problem is fixed in [Django 2.1](https://github.com/django/django/commit/ee49306176a2d2f1751cb890bd607d42c7c09196). – Micah Yeager Sep 13 '19 at 19:58
56

An alternative that uses create to create the object and save it to the database in one line:

employee = Employee.objects.create(first_name='first', last_name='last', type_id=4)
Jacinda
  • 4,932
  • 3
  • 26
  • 37
1

Just to emphasize something on the accepted answer (based on my experience): When you want to add a value in the "id" field of the foreign key (hope that this is clear), you must add "_id" at the end of the name defined by you in that class.

In this example: employee = Employee(first_name="Name", last_name="Name", type_id=4)

Here "type" refers to "type" defined in the "Employee" class.

Note that if you have defined something like "foo_id", you still must add the "_id" suffix and the result will be "foo_id_id"

PS: I can't comment or do other actions (not enough reputation points)

Alext
  • 11
  • 3