Horje
How to Define Two Fields "Unique" as Couple in Django

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 Django

Setting Up Your Django Project

First, 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
cd 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 = [
...
'reservations',
]
ko

Defining the Model with Unique Together Constraint

In 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.

Python
from django.db import models

class Booking(models.Model):
    table_number = models.IntegerField()
    reservation_time = models.DateTimeField()
    
    class Meta:
        unique_together = ('table_number', 'reservation_time')
        
    def __str__(self):
        return f'Table {self.table_number} at {self.reservation_time}'

Update admin.py file also

Python
from django.contrib import admin
from reservations.models import Booking
# Register your models here.

admin.site.register(Booking)

Creating and Applying Migrations

To create the database table for your model, generate and apply migrations:

python manage.py makemigrations
python manage.py migrate

Createsuperuser

python manage.py createsuperuser

Testing the Unique Constraint

Run the server and testing the unique constraint

Output





Reffered: https://www.geeksforgeeks.org


Python

Related
How to Compare List of Dictionaries in Python How to Compare List of Dictionaries in Python
How to Drop Negative Values in Pandas DataFrame How to Drop Negative Values in Pandas DataFrame
How to Import BeautifulSoup in Python How to Import BeautifulSoup in Python
How to Install BeautifulSoup in Anaconda How to Install BeautifulSoup in Anaconda
Remove Empty Dates from X Axis using Python Plotly Remove Empty Dates from X Axis using Python Plotly

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
20