How to create a composite primary Key in django

 To create a composite primary key based on the first three columns (classdate, course_code, and batch_number), you need to define a unique_together constraint in the model's Meta class. Here's how you can do it:
from django.db import models

class DailyWork(models.Model):
    classdate = models.DateField()
    course_code = models.ForeignKey(Course, on_delete=models.DO_NOTHING)
    batch_number = models.ForeignKey(Batch, on_delete=models.DO_NOTHING)
    s1st = models.CharField(max_length=7)
    s1endt = models.CharField(max_length=7)

    
    class Meta:
        ordering = ['id']
        unique_together = (('classdate', 'course_code', 'batch_number'),)

In this code, unique_together is a tuple of tuples where 
each inner tuple represents the fields that should be unique together. 
In this case, it ensures that the combination of classdate, course_code, and batch_number is unique,
effectively creating a composite primary key.
Make sure to replace Course and Batch with the actual models you are referencing.

Comments

Popular posts from this blog

Basic Web Design with HTML and CSS

Project Web Design Assignment