0

Let's say I have two very basic model classes - for simplicity let's name them a Plan and a Task. My goal is to force every plan to have exactly 4 distinct tasks (order doesn't matter). Is there some good practice for this "many-to-many with a fixed quantity of related instances" case?

from django.db import models


class Task(models.Model):
    name = models.CharField(max_length=20)


class Plan(models.Model):
    name = models.CharField(max_length=20)
    # four_tasks = ?

I searched through Django documentation but there's no answer there (or maybe I didn't know how to search for it). I thought of 4 separate foreign keys (which should be possible by setting related_name for those) in Plan, or maybe standard many-to-many many relations. Both solutions require additional checks to ensure that there are actually 4 different tasks and they look ugly to me.

Seblis
  • 339
  • 4
  • 17
  • Are the tasks always the same? Is the user creating the tasks or are you? Is it possible anywhere for the user to create/assign a 5th task? How are the tasks being assigned? I think you need to answer these questions first. – Adam James Nov 12 '22 at 14:44
  • Tasks are always the same (perhaps few will be added every few months, but I can disregard that for now) and I am creating tasks and add them using django shell. Plan is created by the user and he is choosing the tasks for his plan (from the list static from the perspective of the user). – Seblis Nov 12 '22 at 15:24

1 Answers1

2

In my opinion, from the point of view of databases, the best practice would be to have the 4 separate foreign keys (as you thought) as a primary key (composite key).

This can be achieved in Django using the uniqueConstraint which is the preferable way over unique_together option:

UniqueConstraint provides more functionality than unique_together. unique_together may be deprecated in the future.

EDIT: If you are wondering how to use it, here is an answer

Sunderam Dubey
  • 1
  • 11
  • 20
  • 40
Niko
  • 3,012
  • 2
  • 8
  • 14