Django 自引用多对多模型

Django self referencing many-to-many model


我有一个包含两个字段的简单 Django Jobs 模型;申请人和 applicants_selected.

“申请人”是与用户模型的多对多关系。
我希望“applicants_selected”与同一模型

的申请人字段具有多对多关系

例如:

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

最好的方法是什么?

谢谢

您可以在 ManyToManyFieldthrough=… model [Django-doc] 中创建一个 BooleanField:

from django.conf import settings
from django.db import models

class Job(models.Model):
    applicants = models.ManyToManyField(
        settings.AUTH_USER_MODEL,
        <b>through='Applicant'</b>
    )

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)

因此,您可以将 selected 字段更改为 True,以防候选人 selected。因此,您可以 select select 的申请人:

myjob.applicants.filter(<b>applicant__selected=True</b>)

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.