![]() |
In many applications, you might encounter scenarios where you need to ensure that a pair of fields in a database model must be unique together. For example, if you have a Booking model in a restaurant reservation system, you may want to ensure that the combination of table_number and reservation_time is unique, preventing double bookings for the same table at the same time. In Django, this can be achieved using the unique_together constraint. This article will guide you through creating a small project in Django to demonstrate how to define two fields as a unique couple. Define Two Fields “Unique” as Couple in DjangoSetting Up Your Django ProjectFirst, ensure you have Django installed. If not, you can install it using pip: pip install django Next, create a new Django project: django-admin startproject unique_fields_project Create a new app within your project: python manage.py startapp reservations Add the new app to your INSTALLED_APPS in unique_fields_project/settings.py: INSTALLED_APPS = [ ![]() Defining the Model with Unique Together ConstraintIn your reservations/models.py, define a Booking model with the unique_together constraint: The unique_together constraint ensures that each combination of table_number and reservation_time is unique.
Update admin.py file also
Creating and Applying MigrationsTo create the database table for your model, generate and apply migrations: python manage.py makemigrations Createsuperuser python manage.py createsuperuser Testing the Unique ConstraintRun the server and testing the unique constraint Output |
Reffered: https://www.geeksforgeeks.org
Python |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 20 |