Django Unscientific Benchmark between modpython / modwsgi / aspen and runserver; Misc. Tutorials Django cheat sheet Django & Python Tutorial on Android Use the Django admin for my PHP app Some django gotchas Django’s Undocumented contenttype app Django profiling with hotshot and kcachegrind. When discussing Django ORM optimization tips recently, I realized there wasn't really a quick reference guide for them, so I decided to make one including the tips I find most helpful. You can find the cheat sheet gist here. I also wrote a slightly more in depth blog post about it here, if you're interested. I hope this is helpful to someone. Submit your email to get the Django cheat sheet. If you are interested in updates about videos and articles I write, you can get those as well.
_set is associated with reverse relation on a model.
Django allows you to access reverse relations on a model. By default, Django creates a manager (RelatedManager
) on your model to handle this, named <model>_set, where <model> is your model name in lowercase.
- Django ORM Optimization Tips. Caveats:. Only use optimizations that obfuscate the code if you need to. Not all of these tips are hard and fast rules. Use your judgement to determine what improvements are appropriate for your code.
- Django ORM can be in a way mapped to Elasticsearch DSL. I summarized the comparison of Django ORM and Elasticsearch DSL, mentioned in this article, into a cheat sheet. Print it on a single sheet of paper and use it as a reference for your developments.
Excellent link on StackOverflow here:
https://stackoverflow.com/questions/25386119/whats-the-difference-between-a-onetoone-manytomany-and-a-foreignkey-field-in-d
If we have these models:
Django Orm Cheat Sheet Pdf
2 4 6 | username=models.CharField(max_length=100,unique=True) companies=models.ManyToManyField('Company',blank=True) classCompany(models.Model): |
In Django,
“It doesn’t matter which model has the ManyToManyField, but you should only put it in one of the models — not both.”.
So, to get all the companies associated with a User, we can do:User.companies.all()
But the reverse is a bit tricky. That is, how to get all users associated with a company.
Very easy. Get the reverse relationship using _setcompany.user_set.all()
will return a QuerySet of User objects that belong to a particular company. By default you use modelname_set to reverse the relationship, but you can override this be providing a related_name as a parameter when defining the model, i.e.
Django Orm Get
2 4 6 | username=models.CharField(max_length=100,unique=True) companies=models.ManyToManyField('Company',blank=True,related_name='users') classCompany(models.Model): |
Django Orm Tutorial
Then you can get the reverse without using _set like so:company.users.all()