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
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)
- [Django]-Creating a JSON response using Django and Python
- [Django]-Django filter queryset __in for *every* item in list
- [Django]-Django gives Bad Request (400) when DEBUG = False
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)
- [Django]-Dynamically adding a form to a Django formset
- [Django]-How to get Request.User in Django-Rest-Framework serializer?
- [Django]-How to loop over form field choices and display associated model instance fields