首页 > 解决方案 > Django根据额外条件进行一对多查询

问题描述

我有这样的代码设置:

class User(models.Model):
   email = models.EmailField(_(u'email address'), max_length=255, unique=True, db_index=True, blank=True)

class Verification(models.Model):
   created_by = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='verifications')
   category = models.CharField(choices=constants.VERIFICATION_CATEGORY_CHOICES, default=None, max_length=255)
   status = models.CharField(_(u'verification status'), max_length=255, default=constants.STATUS_PENDING, blank=True, null=True)

现在我需要获取具有“ID”(类别)验证且验证状态为“已批准”的用户列表。我怎样才能做到这一点?

标签: djangodjango-orm

解决方案


你可以这样做(使用related_nameverifications作为反向关系):

 User.objects.filter(verifications__category="ID", verifications_status="APPROVED")

推荐阅读