Django F Expression Practices

F-Expression

Django F Expression Practices

  • An F() object represents the value of a model field, transformed value of a model field, or annotated column.
  • It makes it possible to refer to model field values and perform database operations using them without actually having to pull them out of the database into Python memory.
  • Instead, Django uses the F() object to generate an SQL expression that describes the required operation at the database level.
  • F objects or expression used to reference fields
  • Helps to avoid loading objects into memory, operations are performed in Database
  • Django use F expression to generate an SQL expression
  • Another useful benefit of F() is that having the database - rather than Python - update a field’s value avoids a race condition.

models.py

python manage.py shell
  • F() objects assigned to model fields persist after saving the model instance and will be applied on each save(). So be careful !!!
  • new models and fields

shell

edit models.py

shell

  • When referencing relational fields such as ForeignKey, F() returns the primary key value rather than a model instance.

 

Yorumlar