djangodjango-related-manager

Django One(Many)-To-Many Relation in reusable app


I have a model named Exam. each Exam has a set of users called participants. The only way I found to keep such set in Django is to add a field in User model. But I'd prefer to write this model to be as independent as possible so if later I want to use it again I can do it without changing my User model. So How can I handle having such set without manually modifying the User model fields?


Solution

  • Regarding your comment here is what you could do something like this:

    class Exam(models.Model):
        participants = models.ManyToMany(settings.AUTH_USER_MODEL, through='Participation')
    
    class Participation(models.Model)
        user = models.OneToOneField(settings.AUTH_USER_MODEL)
        exam = models.ForeignKey('Exam')
        active = models.BooleanField(default=False)
    

    Another option would be to use Django's limit_coices_to. It's not transaction-save, but might do the job. You would just limit to choices to all non-related objects.