Take the 2-minute tour ×

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')


  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.

share|improve this question
add comment

2 Answers

up vote 69 down vote accepted


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

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.

share|improve this answer
add comment

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)
share|improve this answer
add comment

Your Answer


