votes up 5

Cannot call delete() after .distinct().

Package:
django
github stars 59414
Exception Class:
TypeError

Raise code

    def delete(self):
        """Delete the records in the current QuerySet."""
        self._not_support_combined_queries('delete')
        if self.query.is_sliced:
            raise TypeError("Cannot use 'limit' or 'offset' with delete().")
        if self.query.distinct or self.query.distinct_fields:
            raise TypeError('Cannot call delete() after .distinct().')
        if self._fields is not None:
            raise TypeError("Cannot call delete() after .values() or .values_list()")

        del_query = self._chain()

        # The delete is actually 2 queries - one to find related objects,
        # and one to delete. Make sure that the discovery of related

Ways to fix

votes up 2 votes down

QuerySet is iterable, and it executes its database query the first time you iterate over it. More information check

Queryset, as seen in the name, allows users to work tables in Database.

distinct - eliminates duplicate rows from the query results.

delete - performs an SQL delete query on all rows.

But one thing here, distinct('field_name') are only work in PostgreSQL.

To create a Django project:

django-admin startproject project_name

We need to create a user or simply let's create an admin user.

python manage.py createsuperuser 

Need to write information about admin.

Username: admin
Email address:
Password:
Password (again):
The password is too similar to the username.
This password is too short. It must contain at least 8 characters.
This password is too common.
Bypass password validation and create user anyway? [y/N]: y
Superuser created successfully.

and next thing is to connect PostgreSQL with Django. Simple change DATABASE in settings.py. Check here

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': ‘<db_name>’,
        'USER': '<db_username>',
        'PASSWORD': '<password>',
        'HOST': '<db_hostname_or_ip>',
        'PORT': '<db_port>',
    }
}

So, to get an error, we can use Django shell.

python manage.py shell

This command allows us to work with the database in the shell.

Then need to import the User table to our code.

>>>from django.contrib.auth.models import User

Define distinct value

>>>def_value = User.objects.distinct('is_staff')
>>> def_value
<QuerySet [<User: admin>]>

After distinct, if we want to delete that value

def_value.delete()

We will get an error

Traceback (most recent call last):
 File "<console>", line 1, in <module>
 File "C:\Users\ENVY\Desktop\python\Fiverr\Exceptions\test1\lib\site-packages\d
jango\db\models\query.py", line 728, in delete
  raise TypeError('Cannot call delete() after .distinct().')
TypeError: Cannot call delete() after .distinct().

To fix that we can use a get to delete what we want.

>>> from django.contrib.auth.models import User
>>> a = User.objects.get()
>>> a
<User: admin>
>>> a.delete()
(1, {'auth.User': 1})

So simply to get an error we can use Django shell

Jul 01, 2021 anonim answer
anonim 13.0k

Add a possible fix

Please authorize to post fix