如何使用Django queryset过滤器创建views.py以比较Django中两个不同表的特定值?

时间:2019-08-09 13:18:22

标签: python django django-models

JOB_TYPE = (
    ('1', "Full time"),
    ('2', "Part time"),
    ('3', "Internship"),
)


class Job(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    title = models.CharField(max_length=300)
    description = models.TextField()
    location = models.CharField(max_length=150)
    type = models.CharField(choices=JOB_TYPE, max_length=10)
    category = models.CharField(max_length=100)
    last_date = models.DateTimeField()
    skillRequired1 = models.CharField(max_length=100, default="")
    skillRequired2 = models.CharField(max_length=100, blank=True, null=True)
    work_experience = models.IntegerField(default=0)
    company_name = models.CharField(max_length=100)
    company_description = models.CharField(max_length=300)
    website = models.CharField(max_length=100, default="")
    created_at = models.DateTimeField(default=timezone.now)
    filled = models.BooleanField(default=False)

    def __str__(self):
        return self.title


class EmployeeProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    title = models.CharField(max_length=300)
    location = models.CharField(max_length=150)
    type = models.CharField(choices=JOB_TYPE, max_length=10)
    work_experience = models.IntegerField(default=0)
    category = models.CharField(max_length=100)
    emailContact = models.CharField(max_length=100, default="")
    skill1 = models.CharField(max_length=100)
    skill2 = models.CharField(max_length=100)
    skill3 = models.CharField(max_length=100, blank=True)
    skill4 = models.CharField(max_length=100, blank=True)
    about_me = models.TextField()
    images = models.ImageField(upload_to='employeeProfiles', default='default.jpg')

    def __str__(self):
        return f'{self.user.first_name} Profile'

我创建了两个数据库表“ Job”,另一个是“ employeeProfile”。我想比较和匹配两个表的“ title”,只想显示Job中存在的“ title”,而不显示“ employeeProfile”中的“ title” '。这两个表位于两个不同的模型中。

1 个答案:

答案 0 :(得分:0)

我会尝试这样的事情:

(可能需要在字段声明中使用default=''blank=True

qs = EmployeeProfile.objects.filter(title='').exclude(user__title='')

您可以解决与双__

的关系

您还可以在标题定义中添加null=True以便使用:

qs = EmployeeProfile.objects.filter(user__title__isnull=False, title__isnull=True)