[Answered ]-Check if item exists in database by field value

1👍

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')

Leave a comment