【问题标题】:django.core.exceptions.FieldDoesNotExist: Raw query must include the primary keydjango.core.exceptions.FieldDoesNotExist:原始查询必须包含主键
【发布时间】:2021-10-30 09:30:31
【问题描述】:

我正在尝试在 django 中进行原始查询,但它似乎不起作用。

当我在 table plus (IDE for databases) 中执行相同的查询时,它正在工作。

这是我的 Django 代码:

class AllCustomerOwnerTransactionView(APIView):
    permission_classes = [IsAuthenticated]
    authentication_classes = [JWTAuthentication]

    def get(self, request):
        query = f"""
SELECT  u_c.name,
       sum(CASE
         WHEN h_te.to_pay_to_customer > h_te.pay_from_customer THEN
          h_te.to_pay_to_customer - h_te.pay_from_customer
         WHEN h_te.pay_from_customer > h_te.to_pay_to_customer THEN
         h_te.pay_from_customer - h_te.to_pay_to_customer
         ELSE 0
       end) as Total,
       u_c.owner_id
FROM home_transactionentries h_te
       INNER JOIN home_transaction h_t
               ON h_te.transaction_id = h_t.id
       INNER JOIN users_customer u_c
               ON u_c.id = h_t.customer_id
WHERE u_c.owner_id = {request.user.id}
GROUP BY u_c.name,
         u_c.owner_id;
        """
        query_set = TransactionEntries.objects.raw(query)

这是我得到的 Traceback:

Traceback (most recent call last):
  File "/home/__neeraj__/.local/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner
    response = get_response(request)
  File "/home/__neeraj__/.local/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/__neeraj__/.local/lib/python3.9/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
    return view_func(*args, **kwargs)
  File "/home/__neeraj__/.local/lib/python3.9/site-packages/django/views/generic/base.py", line 70, in view
    return self.dispatch(request, *args, **kwargs)
  File "/home/__neeraj__/.local/lib/python3.9/site-packages/rest_framework/views.py", line 509, in dispatch
    response = self.handle_exception(exc)
  File "/home/__neeraj__/.local/lib/python3.9/site-packages/rest_framework/views.py", line 469, in handle_exception
    self.raise_uncaught_exception(exc)
  File "/home/__neeraj__/.local/lib/python3.9/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception
    raise exc
  File "/home/__neeraj__/.local/lib/python3.9/site-packages/rest_framework/views.py", line 506, in dispatch
    response = handler(request, *args, **kwargs)
  File "/home/__neeraj__/Documents/programming/merokarobarClone/AccountsBackend/home/views.py", line 73, in get
    for db_data in query_set:
  File "/home/__neeraj__/.local/lib/python3.9/site-packages/django/db/models/query.py", line 1484, in __iter__
    self._fetch_all()
  File "/home/__neeraj__/.local/lib/python3.9/site-packages/django/db/models/query.py", line 1471, in _fetch_all
    self._result_cache = list(self.iterator())
  File "/home/__neeraj__/.local/lib/python3.9/site-packages/django/db/models/query.py", line 1499, in iterator
    raise exceptions.FieldDoesNotExist(
django.core.exceptions.FieldDoesNotExist: Raw query must include the primary ke

这是我在 table plus 中执行的查询:

SELECT u_c.name,
       sum(CASE
         WHEN h_te.to_pay_to_customer > h_te.pay_from_customer THEN
          h_te.to_pay_to_customer - h_te.pay_from_customer
         WHEN h_te.pay_from_customer > h_te.to_pay_to_customer THEN
         h_te.pay_from_customer - h_te.to_pay_to_customer
         ELSE 0
       end) as Total,
       u_c.owner_id
FROM   home_transactionentries h_te
       INNER JOIN home_transaction h_t
               ON h_te.transaction_id = h_t.id
       INNER JOIN users_customer u_c
               ON u_c.id = h_t.customer_id
WHERE  u_c.owner_id = 1
GROUP  BY u_c.name,
          u_c.owner_id;

注意:

h_tehome_transactionentries

h_thome_transaction

u_cuser_customer

home_transactionentries table

home_transaction table

user_customer table

【问题讨论】:

    标签: python sql django postgresql


    【解决方案1】:

    如果你想执行一个不映射到返回模型实例的原始查询(这是异常告诉你的),你需要使用cursor.execute()

    with connection.cursor() as cursor:
        cursor.execute(
            f"""
    SELECT
      u_c.name,
      sum(
        CASE
          WHEN h_te.to_pay_to_customer > h_te.pay_from_customer THEN h_te.to_pay_to_customer - h_te.pay_from_customer
          WHEN h_te.pay_from_customer > h_te.to_pay_to_customer THEN h_te.pay_from_customer - h_te.to_pay_to_customer
          ELSE 0
        end
      ) as Total,
      u_c.owner_id
    FROM
      home_transactionentries h_te
      INNER JOIN home_transaction h_t ON h_te.transaction_id = h_t.id
      INNER JOIN users_customer u_c ON u_c.id = h_t.customer_id
    WHERE
      u_c.owner_id = %s
    GROUP BY
      u_c.name,
      u_c.owner_id;
    """,
            [request.user.id],
        )
        data = cursor.fetchall()  # list of 3-tuples according to your columns
    

    注意使用%s 占位符以避免SQL 注入漏洞。

    顺便说一句,您似乎可以将 Total 列的计算简化为

    sum(abs(h_te.to_pay_to_customer - h_te.pay_from_customer)) as Total
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-21
      • 2020-05-09
      • 2021-02-19
      • 1970-01-01
      • 1970-01-01
      • 2017-06-29
      • 2018-11-14
      • 1970-01-01
      相关资源
      最近更新 更多