Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

One membership for each user for each club

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading