Django:使用另一个表的结果过滤对象?

Cub*_*Eye 0 django django-views

关于如何在Django中做到这一点,我有一个心理上的空白,希望你能提供帮助.

我有一个画廊表,我按类型过滤:

public_galleries = models.Gallery.objects.filter(type = 2).filter(root_gallery__isnull = True)
Run Code Online (Sandbox Code Playgroud)

但我还想看看特定用户的UserGallery表中是否存在该库.我有这个用户列表:

user_galleries = models.UserGallery.objects.select_related().filter(clientuser=request.user.id).filter(gallery__root_gallery__isnull = True)
Run Code Online (Sandbox Code Playgroud)

注意**刚刚开始将Django用于实际项目,因此对这两种语句的任何改进也表示赞赏.

编辑 - 模特:

class Gallery(models.Model):
    """Gallery model"""
    name = models.CharField(u"Gallery name", max_length=120)
    type = models.IntegerField(default=0, choices=TYPE_CHOICES)
    root_gallery = models.ForeignKey("self", blank=True, null=True)
    """ Other Fields"""

class UserGallery(models.Model):
    """Model to link Gallery and ClientUser"""
    gallery = models.ForeignKey(Gallery)
    clientuser = models.ForeignKey(ClientUser)
    owner = models.BooleanField(default=False)
Run Code Online (Sandbox Code Playgroud)

May*_*esh 5

Gallery.objects.filter(type = 2).filter(root_gallery__isnull = True).exclude(id__in = [x.id for x in request.user.usergallery_set()])
Run Code Online (Sandbox Code Playgroud)

应该这样做.