有什么办法可以在Django模型中进行过滤?

时间:2020-03-17 09:05:37

标签: python django django-models

我创建自定义帐户模型,并添加诸如 is_student,is_teacher 之类的视图列。因此,我在另一个应用程序中创建了另一个类,以便如何在模型中过滤类似的内容。

Accounts apps models.py

class Account(AbstractBaseUser):
    email                   = models.EmailField(verbose_name="email", max_length=60, unique=True)
    username                = models.CharField(max_length=30, unique=True)
    date_joined             = models.DateTimeField(verbose_name='date joined', auto_now_add=True)
    last_login              = models.DateTimeField(verbose_name='last login', auto_now=True)
    is_admin                = models.BooleanField(default=False)
    is_active               = models.BooleanField(default=True)
    is_staff                = models.BooleanField(default=False)
    is_superuser            = models.BooleanField(default=False)
    is_student              = models.BooleanField(default=False)
    is_teacher              = models.BooleanField(default=False)

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['username']

    objects = MyAccountManager()

主要应用模型。py

from accounts.models import Account
a = Account.objects.filter(is_student=True)
class Students(models.Model):
    student = models.ManyToManyField(a, on_delete=models.CASCADE)

我想要的是在Student表和Accounts之间建立联系

(仅那些is_student = True)

1 个答案:

答案 0 :(得分:0)

甚至认为这是不可能的。表在数据之前存在。因此,您创建表,然后插入数据。您可以决定在哪个数据后插入。
并且不要命名您的表的复数形式:Students

这是一个解决方案:

class Student(models.Model):
    # this means a student can have many accounts and an account can be linked with many students 
    account = models.ManyToManyField(Account, related_name="students", on_delete=models.CASCADE)

与许多学生建立联系可能不是一个好主意。
我会的:

class Student(models.Model):
    # this means a student can only have one  account and an account can only be linked with one student
    account = models.OneToOneField(Account, related_name="student", on_delete=models.CASCADE)

如果您想获得活跃用户,只需在您的视图中执行即可:

active_students = Student.objects.filter(account__is_active=True)