I am getting error when to limit foreign keys
Goal: I want to limit(20) the number of Students per Group.
I was trying to make validation (based on this question - Limit number of foreign keys), but got a problem - it's working when I am trying to make 21 Student in group in my Django admin panel, but when I'm trying to change login(or other parameters) of Student (the group in this moment has 20 Students), who already in group it turns up an error, because it seems like I already have 20 students and trying to add new one
def validate_number_of_students(value):
if User.objects.filter(group=value).count() >= 20:
raise ValidationError('Already 20 students in group (20)')
class User(AbstractUser):
role = models.CharField(max_length=max([len(role[0]) for role in ROLES]),
choices=ROLES,
default=USER,
)
group = models.ForeignKey('structure.Group',
on_delete=models.SET_NULL,
related_name='users',
blank=True,
null=True,
validators=(validate_number_of_students, )
)
I tried to use this method with constraint (limit number of foreign key using Django CheckConstraint) but get an error, maybe I'm doing something wrong? (I have two apps - structure with Group model and users with User model)
models.CheckConstraint(
name="limit_students_in_group",
check=IntegerLessThan(
models.Count("group", filter=models.Q(group=models.F("group"))),
20),
)