Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Django:使用另一个表的结果筛选对象?_Django_Django Views - Fatal编程技术网

Django:使用另一个表的结果筛选对象?

Django:使用另一个表的结果筛选对象?,django,django-views,Django,Django Views,在Django如何做到这一点,我在脑子里还是个空白,希望你能帮助我 我有一个按类型筛选的图库表: public_galleries = models.Gallery.objects.filter(type = 2).filter(root_gallery__isnull = True) 但我还想看看特定用户的UserGallery表中是否不存在该库。我为用户提供了以下库列表: user_galleries = models.UserGallery.objects.select_related(

在Django如何做到这一点,我在脑子里还是个空白,希望你能帮助我

我有一个按类型筛选的图库表:

public_galleries = models.Gallery.objects.filter(type = 2).filter(root_gallery__isnull = True)
但我还想看看特定用户的UserGallery表中是否不存在该库。我为用户提供了以下库列表:

user_galleries = models.UserGallery.objects.select_related().filter(clientuser=request.user.id).filter(gallery__root_gallery__isnull = True)
注**刚刚开始在一个实际项目中使用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)

应该这样做。

我要感谢Mayuresh,感谢他的帮助

我不知道为什么会出现这样的错误,但我找到了解决方案:

private_galleries = models.Gallery.objects.filter(type = 1).filter(root_gallery__isnull = True).exclude(id__in = [x.gallery.id for x in user_galleries])

这个答案对于中等数量的
用户库
都不起作用,因为您每次都要将它们全部加载到一个列表中

更好的方法是使用QuerySet的方法,它允许您在SQL中为
WHERE
子句指定附加条件

从Django文档:

您可以使用WHERE定义显式SQLWHERE子句——可能是为了执行非显式联接。可以使用tables将表手动添加到SQLFROM子句中

就你的情况来说

private_galleries = Gallery.objects.filter(type=1, root_gallery__isnull=True) \
    .extra(where=['''
        yourapp_gallery.id NOT IN (SELECT id FROM 
            ...long query used to generate user_galleries...  )
    '''])
会有用的。不幸的是,这意味着将生成
user\u galleries
的查询转录到SQL中,因此您需要决定是否值得在每次查询中将该列表加载到内存中时进行干式/可维护性权衡。我怀疑除了少量的
user\u库
之外,它是什么

请注意,
where=
arg获取字符串列表


更多信息请参阅邮件列表

对于任何涉及查询的Django问题,最好包括模型。好吧,这让我大部分时间都在那里,我最终得到了
public\u Gallery=models.Gallery.objects.filter(type=2).filter(root\u Gallery\u isnull=True).exclude(id\u in=[x.Gallery.id for x in user\u Gallery])
private_galleries = Gallery.objects.filter(type=1, root_gallery__isnull=True) \
    .extra(where=['''
        yourapp_gallery.id NOT IN (SELECT id FROM 
            ...long query used to generate user_galleries...  )
    '''])