0

Suppose I have a model called User, with a field called name. How can I determine whether a User instance, with a particular name Andrew, already exists in the database?

I could do:

matched_users = User.objects.filter(name = 'Andrew')
if matched_users.count() == 0:
    # It does not exist
else:
    # It does exist

But is there a way I can do this in one line, without having to retrieve all instances and then count them?

alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
Karnivaurus
  • 22,823
  • 57
  • 147
  • 247
  • 1
    This already does what you want. Because Django lazily evaluates querysets, it won't retrieve all instances. The database won't be hit until the `count()` call. That said, `exists()` is the more straightforward way. – Kevin Christopher Henry Jul 04 '14 at 18:58

2 Answers2

4

Yes, you can use exists():

if User.objects.filter(name='Andrew').exists():
    # do something

But there might me multiple users with same name. You might want to lookup on some unique field e.g. username or email

If you want to insist using count method then it can be written as:

if User.objects.filter(name = 'Andrew').count() > 0:
    # exists
Aamir Rind
  • 38,793
  • 23
  • 126
  • 164
2

Ask for forgiveness: let it try to create a duplicate and handle IntegrityError exception.

You need to define unique=True on the name field for this to work:

Field.unique

This is enforced at the database level and by model validation. If you try to save a model with a duplicate value in a unique field, a django.db.IntegrityError will be raised by the model’s save() method.

Community
  • 1
  • 1
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • Asking for forgiveness is not so straightforward when it comes to interacting with the database. For example, an `IntegrityError` will spoil the current transaction regardless of whether or not you catch it. – Kevin Christopher Henry Jul 04 '14 at 19:04
  • @KevinChristopherHenry I could have posted `exists()` solution, but I just like to provide alternative solutions viewing from another perspective. And, depending on the use case - for example, if the OP checks for the existence of a user with the same name before creating a user, both solutions have right to exist. Less roundtrips to the database if this is the case. Thank you for your feedback. – alecxe Jul 06 '14 at 04:02
  • 1
    My point is just to warn readers against blindly applying the EAFP idiom - so familiar to Python developers - without carefully thinking about the interactions with the database. I agree with you that for some use cases this will be the more efficient solution. – Kevin Christopher Henry Jul 06 '14 at 05:21