nandesuka
nandesuka

Reputation: 799

Check if item exists in database by field value

I have a class called Product and I want to check if there is already a product in the database with the same title.

class Product(models.Model):
  title = models.CharField(max_length=255)
  ...


for (something in something):
  check if db contains product with a title of 'Some Product'

Upvotes: 1

Views: 1451

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476813

You can work with .exists() [Django-doc]:

Product.objects.filter(title='Some Product').exists()

It might however be better to enforce uniqness at the database level, with unique=True [Django-doc]:

class Product(models.Model):
    title = models.CharField(max_length=255, unique=True)

then if the database enforces (most databases do), it will simply be impossible to create a new Product with the same title.

You can also obtain a Product, or create it if it does not yet exists, with .get_or_create(…) [Django-doc]:

my_prod, created = Product.objects.get_or_create(title='Some Product')

Upvotes: 1

Related Questions