How to rename items in values() in Django?

From django>=1.8 you can use annotate and F object from django.db.models import F MyModel.objects.annotate(renamed_value=F(‘cryptic_value_name’)).values(‘renamed_value’) Also extra() is going to be deprecated, from the django docs: This is an old API that we aim to deprecate at some point in the future. Use it only if you cannot express your query using other queryset methods. If … Read more

How to create an object for a Django model with a many to many field?

You cannot create m2m relations from unsaved objects. If you have the pks, try this: sample_object = Sample() sample_object.save() sample_object.users.add(1,2) Update: After reading the saverio’s answer, I decided to investigate the issue a bit more in depth. Here are my findings. This was my original suggestion. It works, but isn’t optimal. (Note: I’m using Bars … Read more

How to view corresponding SQL query of the Django ORM’s queryset?

Each QuerySet object has a query attribute that you can log or print to stdout for debugging purposes. qs = Model.objects.filter(name=”test”) print(qs.query) Note that in pdb, using p qs.query will not work as desired, but print(qs.query) will. If that doesn’t work, for old Django versions, try: print str(qs.query) Edit I’ve also used custom template tags … Read more

Convert Django Model object to dict with all of the fields intact

There are many ways to convert an instance to a dictionary, with varying degrees of corner case handling and closeness to the desired result. 1. instance.__dict__ instance.__dict__ which returns {‘_foreign_key_cache’: <OtherModel: OtherModel object>, ‘_state’: <django.db.models.base.ModelState at 0x7ff0993f6908>, ‘auto_now_add’: datetime.datetime(2018, 12, 20, 21, 34, 29, 494827, tzinfo=<UTC>), ‘foreign_key_id’: 2, ‘id’: 1, ‘normal_value’: 1, ‘readonly_value’: 2} This … Read more

What’s the difference between select_related and prefetch_related in Django ORM?

Your understanding is mostly correct. You use select_related when the object that you’re going to be selecting is a single object, so OneToOneField or a ForeignKey. You use prefetch_related when you’re going to get a “set” of things, so ManyToManyFields as you stated or reverse ForeignKeys. Just to clarify what I mean by “reverse ForeignKeys” … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)