Home > Enterprise >  One membership for each user for each club
One membership for each user for each club

Time:08-06

I'm creating models to manage clients and sports centers. Each customer can be enrolled in several centers only once of course. how should i proceed for this?

class Membership(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='memberships')
    club = models.ForeignKey(Club, on_delete=models.CASCADE, related_name='memberships')
    points = models.PositiveIntegerField(default=0, blank=True, null=True)
    sub_date = models.DateField(auto_now_add=True)

    #other...

If I proceed in this way it is possible to create multiple subscriptions of the user to the same club. How can I solve the problem?

CodePudding user response:

Use unique_together in the model Meta so that a Membership object cannot have the same user and club as another object:

class Membership(models.Model):
    ...
    class Meta:
        unique_together = ['user', 'club']

This will return an error if you use a form or the Django admin to create a membership that already exists with that user/club.

CodePudding user response:

Use m2m relationship.

field = models.ManyToManyField(Your_model)
  • Related