optimization - Django: Set foreign key using integer? -


Is there a way to set foreign key relationships using a model's integer ID? It will be for customizable purposes. For example, suppose I have an employee model:

  class employee (model. Model): first_name = models.CharField (max_length = 100) last_name = models.CharField (max_length = 100) ) Type = Model Ferrinki ('employee type')  

and

  employee type (models.Model): Type = models.CharField (max_length = 100)  

I need flexibility to be an unlimited employee type, but there will be only one type of possibility in the deployed app, so I'm wondering if there is a way to hardcode the ID and in this way The relationship sets. In this way I can escape the DB call to get the employee type object first.

Yes:

  employee = employee (first_name = "name" , Last_name = "name") employee Type_ind = 4 employee.seave ()  

Foreigner fields at the end store their values ​​in an attribute with _id Which you can reach directly to the database visits.

_id version is a specially useful aspect of a foreign Django, one is that should be known at all times and timely, Should be used on time.

Warning:

@RuneKaagaard tells that employee.type is not correct in recent Django versions, Even after calling employee.save () (it keeps its old value). Using it will definitely defeat the purpose of the above optimization, but I like an accidental additional question to be wrong. So be careful, when you have finished working on your example (like employee ), then use it.


Comments