click
click

Reputation: 2113

Django : Limit records in database based on foreign key

I would like to limit the number of rows in MyTable to 2 per user

class MyTable(models.Model):
    user = models.ForeignKey(User)
    submission = models.CharField(max_length=100)

Is it better to override the save method or check this in form validation? If it's save method, how do I return an error to the user?

Upvotes: 2

Views: 519

Answers (1)

dekomote
dekomote

Reputation: 4017

Use the clean method to check if there are already 2 rows in the table per user.

def clean(self):
    if MyTable.objects.filter(user=self.user).count()>=2:
        raise ValidationError('Only 2 entries per user allowed')

Upvotes: 2

Related Questions