[Fixed]-Django models – assign id instead of object

28👍

The answer to your question is: YES.

Django will hit the database (at least) 3 times, 2 to retrieve the two User objects and a third one to commit your desired information. This will cause an absolutelly unnecessary overhead.

Just try:

BlackListEntry.objects.create(user_banned_id=int(user_id),user_banning_id=int(banning_id))

These is the default name pattern for the FK fields generated by Django ORM. This way you can set the information directly and avoid the queries.

If you wanted to query for the already saved BlackListEntry objects, you can navigate the attributes with a double underscore, like this:

BlackListEntry.objects.filter(user_banned__id=int(user_id),user_banning__id=int(banning_id))

This is how you access properties in Django querysets. with a double underscore. Then you can compare to the value of the attribute.

Though very similar, they work completely different. The first one sets an atribute directly while the second one is parsed by django, that splits it at the ‘__’, and query the database the right way, being the second part the name of an attribute.

You can always compare user_banned and user_banning with the actual User objects, instead of their ids. But there is no use for this if you don’t already have those objects with you.

Hope it helps.

0👍

I do believe that when you fetch the users, it is going to hit the db…

To avoid it, you would have to write the raw sql to do the update using method described here:

https://docs.djangoproject.com/en/dev/topics/db/sql/

If you decide to go that route keep in mind you are responsible for protecting yourself from sql injection attacks.

Another alternative would be to cache the user_banned and user_banning objects.

But in all likelihood, simply grabbing the users and creating the BlackListEntry won’t cause you any noticeable performance problems. Caching or executing raw sql will only provide a small benefit. You’re probably going to run into other issues before this becomes a problem.

👤Dave

Leave a comment