Search code examples
djangorecursiondjango-modelsmany-to-manydjango-orm

Django self referencing many-to-many model



I have a simple Django Jobs model with two fields; applicants and applicants_selected.

"applicants" is a many to many relationship to the users model.
I want "applicants_selected" to be a many to many relationship to the applicants field of the same model

For Example:

class Job(models.Model):
       applicants = models.ManyToManyField('User', blank=True)
       selected_applicants = models.ManyToManyField('Self.applicants', blank=True)

What's the best way to do this?

Thanks


Solution

  • You can make a BooleanField in the through=… model [Django-doc] of the ManyToManyField:

    from django.conf import settings
    from django.db import models
    
    class Job(models.Model):
        applicants = models.ManyToManyField(
            settings.AUTH_USER_MODEL,
            through='Applicant'
        )
    
    class Applicant(models.Model):
        job = models.ForeignKey(Job, on_delete=models.CASCADE)
        user = models.ForeignKey(
            settings.AUTH_USER_MODEL,
            on_delete=models.CASCADE
        )
        selected = models.BooleanField(default=False)

    You thus can change the selected field to True in case the candidate is selected. You thus can select the applicants that are selected with:

    myjob.applicants.filter(applicant__selected=True)

    Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.