One membership for each user for each club

Question:

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?

Asked By: Pietro Massaro

||

Answers:

Use m2m relationship.

field = models.ManyToManyField(Your_model)
Answered By: ttt

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.

Answered By: 0sVoid
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.