Django: Set foreign key using integer?

后端 未结 2 841
独厮守ぢ
独厮守ぢ 2020-11-28 03:57

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 mod

相关标签:
2条回答
  • 2020-11-28 04:16

    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)
    
    0 讨论(0)
  • 2020-11-28 04:20

    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:

    @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).

    0 讨论(0)
提交回复
热议问题