0

I need to make sure the entry does not have the same project and case id.

How is the best way to prevent a duplicate entry?

Here the project can not have the same case twice.

class Cases(models.Model ):

    project = models.ForeignKey ( Project, on_delete = models.CASCADE )
    case = models.ForeignKey ( Case, on_delete = models.CASCADE )
    active = models.BooleanField ( default = 1 )

Thank you.

diogenes
  • 1,865
  • 3
  • 24
  • 51
  • check this https://stackoverflow.com/questions/2201598/how-to-define-two-fields-unique-as-couple – Rohan Mar 25 '19 at 04:36

1 Answers1

2

You can use unique_together in Meta class in you model as below.

class Cases(models.Model ):

    project = models.ForeignKey ( Project, on_delete = models.CASCADE )
    case = models.ForeignKey ( Case, on_delete = models.CASCADE )
    active = models.BooleanField ( default = 1 )

    class Meta:
        unique_together = ('project', 'case')

This will set unique constraint on project_id and case_id.

Devang Padhiyar
  • 3,427
  • 2
  • 22
  • 42