DEV Community

Discussion on: 666 Django projects checked for inefficient database queries. Over half had these 4 anti-patterns

Collapse
 
danilovmy profile image
Maxim Danilov • Edited

wtf man? Are you really think that advice "Not use foreign keys directly" help you?
NOT. Its wrong solution!
Try to imagine something like that:

def check_hounds(pk, farm_ids):
    if HoundsModel.objects.filter(pk=pk, hound__farm__id__in=farm_ids).exists():
        return "Ja! it is really better than before!!!"
Enter fullscreen mode Exit fullscreen mode

text
if queryset.count() > 0: is not pythonic.
Somebody who work with python, wrote if queryset.count():

Using len(queryset) is not bad, if you work with objects from queryset after len. Django put furst 25 objects as default in cache, and not ask DB again. It can be wery useful in high-load project.

and, of course, used object manager directly in code is wery bad practice.

it should be:

def check_hounds(*args, **kwargs):
    if hound_manager.check_hounds_at_home(*args, **kwargs):
Enter fullscreen mode Exit fullscreen mode

i work with django many Years, if you want, we can talk about work together.

Collapse
 
codereviewdoctor profile image
Code Review Doctor • Edited

The example code is imperfect, but the message I'm conveying is not "use my code". The message I'm trying to convey is "use foreign key values directly if you have to use foreign keys" - which is what Django docs themselves suggesting doing.

The advice of "use foreign keys directly" is fine, but yes I agree the way I illustrate the problem has other issues that are outside of scope of the purpose of the point I'm making

Using len(queryset) is not bad, if you work with objects from queryset after le

Agreed, I make that point in other words too: "Having said that though, if the records will need reading after the length is checked, then len(queryset) can be valid."