Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possible causes for error: Field cannot be both deferred and traversed using select_related at the same time?

I am trying to use graphene-django-optimizer to remove some of the unnecessary queries. It worked quite well until one certain field where I get this error message Field User.company cannot be both deferred and traversed using select_related at the same time. The only difference with this field is that it is models.OneToOne instead of models.ForeignKey. Why Django make this field deferred? Is it possible to disable field being deferred?

like image 964
Aleksey Avatar asked Mar 13 '20 10:03

Aleksey


1 Answers

If you do this:

queryset.select_related('some_fk_field').only('another_field')

You may miss that there is a conflict. You are telling Django ORM to include some_fk_field, but you are also telling it to limit the query to only retrieve another_field, so it complains it can't do it. You use .only() to exclude absolutely everything that is not detailed, but .select_related() is trying to do the opposite requesting some extra elements. To make it even clearer (and this is how I found out), here is the Django source code that handles this case:

    if load_fields:
        if field.attname not in load_fields:
            if restricted and field.name in requested:
                raise InvalidQuery("Field %s.%s cannot be both deferred"
                                   " and traversed using select_related"
                                   " at the same time." %
                                   (field.model._meta.object_name, field.name))

Source: https://docs.djangoproject.com/en/2.1/_modules/django/db/models/query_utils/

like image 112
Emilio Avatar answered Nov 16 '22 16:11

Emilio