Search code examples
pythondjangodjango-queryset

Checking for empty queryset


I want to confirm is this the right way to check for empty queryset, and if it is why am I having a UNIQUE constraint error.

syn_check= Synonym.objects.filter(MD.objects.get(**filter_dict), synonym_type=Stype.objects.filter(description=values.capitalize().strip()), synonym_name=key)
if not syn_check:
    print 'unavailable synonym', key, values
    syn = Synonym()
    syn.synonym_type=Stype.objects.filter(description=values.capitalize().strip()
    syn.synonym_name = key.strip()
    syn.save()

Am I doing anything that is weird? I also used if not syn_check.count() and I had the same problem.

Here is the traceback :

    Traceback (most recent call last):
  File "manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/home/project/.virtualenvs/project/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 385, in execute_from_command_line
    utility.execute()
  File "/home/project/.virtualenvs/project/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 377, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/home/project/.virtualenvs/project/local/lib/python2.7/site-packages/django/core/management/base.py", line 288, in run_from_argv
    self.execute(*args, **options.__dict__)
  File "/home/project/.virtualenvs/project/local/lib/python2.7/site-packages/django/core/management/base.py", line 338, in execute
    output = self.handle(*args, **options)
  File "/home/project/PycharmProjects/project/project/management/commands/back_populate_data.py", line 53, in handle
    loaded_syn = data_loaded_syn4_pubchem(synonym_decoded, filter_dict)
  File "/home/project/PycharmProjects/project/project/lookup_data.py", line 203, in data_loaded_syn4_pubchem
    mol_syn_ob.save()
  File "/home/project/.virtualenvs/project/local/lib/python2.7/site-packages/django/db/models/base.py", line 589, in save
    force_update=force_update, update_fields=update_fields)
  File "/home/project/.virtualenvs/project/local/lib/python2.7/site-packages/django/db/models/base.py", line 617, in save_base
    updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
  File "/home/project/.virtualenvs/project/local/lib/python2.7/site-packages/django/db/models/base.py", line 698, in _save_table
    result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
  File "/home/project/.virtualenvs/project/local/lib/python2.7/site-packages/django/db/models/base.py", line 731, in _do_insert
    using=using, raw=raw)
  File "/home/project/.virtualenvs/project/local/lib/python2.7/site-packages/django/db/models/manager.py", line 92, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/home/project/.virtualenvs/project/local/lib/python2.7/site-packages/django/db/models/query.py", line 921, in _insert
    return query.get_compiler(using=using).execute_sql(return_id)
  File "/home/project/.virtualenvs/project/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 921, in execute_sql
    cursor.execute(sql, params)
  File "/home/project/.virtualenvs/project/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 81, in execute
    return super(CursorDebugWrapper, self).execute(sql, params)
  File "/home/project/.virtualenvs/project/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 65, in execute
    return self.cursor.execute(sql, params)
  File "/home/project/.virtualenvs/project/local/lib/python2.7/site-packages/django/db/utils.py", line 94, in __exit__
    six.reraise(dj_exc_type, dj_exc_value, traceback)
  File "/home/project/.virtualenvs/project/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 65, in execute
    return self.cursor.execute(sql, params)
  File "/home/project/.virtualenvs/project/local/lib/python2.7/site-packages/django/db/backends/sqlite3/base.py", line 485, in execute
    return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: UNIQUE constraint failed: project_synonym.molecule_id, project_synonym.synonym_name, project_synonym.synonym_type_id

Thanks


Solution

  • Checking the queryset as you are doing is fine.

    if not syn_check:
    

    However, it is not as efficent as it could be, you are loading all the objects from the database, when all you want to know is whether the queryset is empty or not.

    It would be better to use count(),

    if not syn_check.count():
    

    and even better to use exists()

    if not syn_check.exists():
    

    The problem in your code is where you define the queryset

    syn_check = Synonym.objects.filter(MD.objects.get(**filter_dict), synonym_type=Stype.objects.filter(description=values.capitalize().strip()), synonym_name=key)
    

    The filter() method accepts either Q objects as args, or keyword arguments. It doesn't make sense to pass the model instance from MD.objects.get(...) as a positional argument.