Django中RawQuerySets和QuerySet的联合和交集

时间:2014-07-19 23:27:38

标签: python django django-queryset

是否有可能以某种方式将RawQuerySet转换为QuerySet或以__and__方式模拟__or__ QuerySet方法RawQuerySet这样我就能得到RawQuerySetQuerySet的联合和交集?

1 个答案:

答案 0 :(得分:1)

link最终帮了我很多。

完整摘录:

from django.db import connection, models

class MyManager(Manager):
    def raw_as_qs(self, raw_query, params=()):
        """Execute a raw query and return a QuerySet.  The first column in the
        result set must be the id field for the model.
        :type raw_query: str | unicode
        :type params: tuple[T] | dict[str | unicode, T]
        :rtype: django.db.models.query.QuerySet
        """
        cursor = connection.cursor()
        try:
            cursor.execute(raw_query, params)
            return self.filter(id__in=(x[0] for x in cursor))
        finally:
            cursor.close()


class MyModel(models.Model):
    objects = MyManager()