时间:2010-07-25 08:42:23

标签: python django

4 个答案:

答案 0 :(得分:9)

简短回答:在某些情况下 - 是的。

当构建LEFT JOIN与GenericForeignKey时,Django调用 GenericRelation.get_extra_restriction使用“content_type_id”限制为ON子句添加额外条件。

对于“ForeignKey”,此方法也由返回无。

调用

如果您设法组织代码以在特定时间获得适当的限制参数,则可以使用此地点为ON子句添加额外限制。

class UserForeignKey(models.ForeignKey):

    def get_extra_restriction(self, where_class, alias, related_alias):
        field = self.model._meta.get_field('user')
        cond = where_class()
        # Here is a hack to get custom condition parameters
        value = SomeContextManager.get_needed_value()

        lookup = field.get_lookup('exact')(field.get_col(related_alias), value)
        cond.add(lookup, 'AND')
        return cond

class WatchList(models.Model):

    user = UserForeignKey(User)

答案 1 :(得分:8)

在Django v2.0中使用FilteredRelation

Post.objects.annotate(
    t=FilteredRelation(
        'watchlist', condition=Q(watchlist__user_id=1)
).filter(t__field__in=...)

答案 2 :(得分:2)

答案 3 :(得分:1)