pythondjangomodel

Limiting amount of objects user can add in another object


I just have a quick question: I would like to limit exercises in training unit to 3-5 exercises , and limit training units in training plan to 12 training units, so the user will not add an infinite number of exercises, or infinite number of training units in a plan?

class TrainingPlan(models.Model):
    user= models.ForeignKey(User, on_delete=models.CASCADE)
    nameoftheplan = models.CharField(verbose_name="Name of the plan",max_length=20, null=True)
    Squat1RM = models.PositiveIntegerField(verbose_name="100%RM in squat",default=0, blank=True, null=True)
    DeadliftT1RM =models.PositiveIntegerField(verbose_name="100%RM maximal repetition in deadlift",default=0, blank=True, null=True)
    Benchpress1RM = models.PositiveIntegerField(verbose_name="100%RM maximal repetition in benchpress",default=0, blank=True, null=True)
    mesocycle= models.CharField(max_length=40, choices=MESOCYCLE_CHOICES,default=MESOCYCLE_GPP)
    timeoftheplan= models.CharField(max_length=40,choices=TIME_CHOICE,default=TIME_WEEK3 )

    def __str__(self):
        return str(self.nameoftheplan)

class TrainingUnit(models.Model):
    trainingplan=models.ForeignKey(TrainingPlan, on_delete=models.CASCADE)
  

class Exercise(models.Model):
    trainingunit=models.ForeignKey(TrainingUnit,on_delete=models.CASCADE)
    exercisename=models.CharField(max_length=100,verbose_name="Exercise",choices=EXERCISE_CHOICES)
    exercisesets=models.IntegerField(choices=SETSCHOICES)
    exercisereps=models.IntegerField(choices=REPCHOICES)

Solution

  • when you handle the user post request you can use objects.filter().count() or objects.all().count() the idea in count() you can apply it on any query you want, in this way you will check how many value you have in database based on condition after that you can accept user post request or rias an error