gpt4 book ai didi

python - Django REST 框架查询集对象没有属性 pk

转载 作者:行者123 更新时间:2023-12-05 09:17:20 26 4
gpt4 key购买 nike

我正在构建一个更大的基于 Django 的网络应用程序,但我遇到了一个应该返回一些数据的 API View 的阻塞问题。

我的应用程序有一个模型 (mail.models.Message) 和一个匹配的序列化程序和 View 集。

对于报告功能,我需要获取经过过滤的结果集,并因此创建了一个单独的 rest_framework.views.APIView 用于报告目的。该模型位于一个应用程序中,而报告位于另一个应用程序中。

这是模型:

class Message(models.Model):
class Meta:
ordering = ('-timestamp',)
get_latest_by = 'timestamp'

id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
from_address = models.CharField("From", max_length=511, blank=True, default="", db_index=True)
from_domain = models.CharField(max_length=255, blank=True, default="", db_index=True)
to_address = models.CharField("To", max_length=511, blank=True, default="", db_index=True)
to_domain = models.CharField(max_length=255, blank=True, default="", db_index=True)
subject = models.TextField(blank=True, default="", db_index=True)
client_ip = models.GenericIPAddressField("Client IP", db_index=True, null=True)
mailscanner_hostname = models.CharField(max_length=255, db_index=True)
spam_score = models.DecimalField(db_index=True, default=0.00, max_digits=7, decimal_places=2)
mcp_score = models.DecimalField(db_index=True, default=0.00, max_digits=7, decimal_places=2)
timestamp = models.DateTimeField(db_index=True)
size = models.FloatField(default=0)
token = models.CharField(max_length=255, null=True)
mailq_id = models.TextField("Mailqueue identification", null=True)
whitelisted = models.BooleanField(db_index=True, default=False)
blacklisted = models.BooleanField(db_index=True, default=False)
is_spam = models.BooleanField(db_index=True, default=False)
is_mcp = models.BooleanField(db_index=True, default=False)
is_rbl_listed = models.BooleanField("Is RBL listed", db_index=True, default=False)
quarantined = models.BooleanField(db_index=True, default=False)
infected = models.BooleanField(db_index=True, default=False)
released = models.BooleanField(db_index=True, default=False)

def __str__(self):
return str(self.id) + "[" + str(self.from_address) + " to " + str(self.to_address) + "]"

以及匹配的序列化器:

class MessageSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Message
fields = (
'id',
'url',
'from_address',
'from_domain',
'to_address',
'to_domain',
'subject',
'client_ip',
'mailscanner_hostname',
'spam_score',
'timestamp',
'size',
'token',
'whitelisted',
'blacklisted',
'is_spam',
'is_rbl_listed',
'quarantined',
'infected'
)

模型上有很多索引来提高搜索和过滤的性能,但我已经排除了这些。

为了报告,我创建了这个特殊 View :

class MessageListApiView(ReportApiView):
serializer_class = MessageSerializer
queryset = Message.objects.all()

def get_queryset(self):
if self.request.method == 'POST':
filters = self.request.data
return MessageQuerySetFilter.filter(MessageQuerySetFilter, self.queryset, filters)
else:
return self.queryset


def post(self, request, format=None):
filters = request.data
qs = self.get_queryset()
serializer = MessageSerializer(qs, context={'request': request})
return Response(serializer.data, 200)

get_queryset 中,我使用了一个特殊的类,该类的唯一目的是对查询集应用适当的过滤并返回它。进行一些测试后,我发现问题发生在我必须返回 Response 时。

我得到这个回溯:

Internal Server Error: /api/reports/messages/
Traceback (most recent call last):
File "/Users/kenneth/Code/mailware/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner
response = get_response(request)
File "/Users/kenneth/Code/mailware/lib/python3.6/site-packages/django/core/handlers/base.py", line 128, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/Users/kenneth/Code/mailware/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/kenneth/Code/mailware/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/Users/kenneth/Code/mailware/lib/python3.6/site-packages/django/views/generic/base.py", line 69, in view
return self.dispatch(request, *args, **kwargs)
File "/Users/kenneth/Code/mailware/lib/python3.6/site-packages/rest_framework/views.py", line 494, in dispatch
response = self.handle_exception(exc)
File "/Users/kenneth/Code/mailware/lib/python3.6/site-packages/rest_framework/views.py", line 454, in handle_exception
self.raise_uncaught_exception(exc)
File "/Users/kenneth/Code/mailware/lib/python3.6/site-packages/rest_framework/views.py", line 491, in dispatch
response = handler(request, *args, **kwargs)
File "/Users/kenneth/Code/mailware/src/reports/views.py", line 44, in post
return Response(serializer.data, 200)
File "/Users/kenneth/Code/mailware/lib/python3.6/site-packages/rest_framework/serializers.py", line 537, in data
ret = super(Serializer, self).data
File "/Users/kenneth/Code/mailware/lib/python3.6/site-packages/rest_framework/serializers.py", line 262, in data
self._data = self.to_representation(self.instance)
File "/Users/kenneth/Code/mailware/lib/python3.6/site-packages/rest_framework/serializers.py", line 504, in to_representation
ret[field.field_name] = field.to_representation(attribute)
File "/Users/kenneth/Code/mailware/lib/python3.6/site-packages/rest_framework/relations.py", line 376, in to_representation
url = self.get_url(value, self.view_name, request, format)
File "/Users/kenneth/Code/mailware/lib/python3.6/site-packages/rest_framework/relations.py", line 312, in get_url
lookup_value = getattr(obj, self.lookup_field)
AttributeError: 'QuerySet' object has no attribute 'pk'
[19/Jan/2018 20:05:24] "POST /api/reports/messages/ HTTP/1.1" 500 16389

上面的APIView类继承了一个自定义的基类,也就是继承了rest_framework.views.APIView类。此类称为 ReportApiView 并简单地设置 paginator_classpermission_class

class ReportApiView(APIView):
permission_classes = (IsAuthenticated,)
pagination_class = PageNumberPaginationWithPageCount

MessageListApiView post 方法中 return 行似乎出错了,但我找不到它不起作用的原因

最佳答案

您需要将 many=True 添加到序列化程序查询集中:

serializer = MessageSerializer(qs, many=True, context={'request': request})

关于python - Django REST 框架查询集对象没有属性 pk,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48348267/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com