0

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?

Matrix
  • 98
  • 1
  • 11
  • Can the user really have one exam only? Are you sure you don't want to use a many2many? – codingjoe Mar 13 '15 at 15:32
  • BTW, don't be afraid to modify the user model. It's actually easier to use a customer model right from the beginning. – codingjoe Mar 13 '15 at 15:33
  • I wanted each user to have at most one active exam at any moment. He can switch between exams but can't take two exam at the same time. However many to many relation works just as well, so I'll edit the post. Thanks – Matrix Mar 13 '15 at 15:40
  • I think there are a lot of situations when it's more logical to have such feature. Since this field is basically related to app Exam and has nothing to do with application related to authentication process. (Also by adding such field I'll be unable to use the authentication app as a reusable app for the future). I know editing user model is the easiest way but I would like to know if there is any better way to do it? – Matrix Mar 13 '15 at 15:47

1 Answers1

1

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.

codingjoe
  • 1,210
  • 15
  • 32
  • 1
    [Django 3.1 link `ForeignKey.limit_choices_to`](https://docs.djangoproject.com/en/3.1/ref/models/fields/#django.db.models.ForeignKey.limit_choices_to) – Daniel W. Aug 20 '20 at 22:08
  • @DanielW. Thanks, I updated the answer to point to the latest stable version. – codingjoe Aug 29 '20 at 16:41