gpt4 book ai didi

具有自定义标识符(不是 pk)的 Django DetailView : Field 'id' expected a number but got 'XQ1wfrpiLVAkjAUL'

转载 作者:行者123 更新时间:2023-12-02 18:42:30 25 4
gpt4 key购买 nike

我使用的是 Django 3.2

我有一个模型和 GCBV 定义如下:

class Foo(models.Model):
identifier = models.CharField(max_length=16, db_index=True)
# ...

class FooDetailView(DetailView):
model = Foo
template_name = 'foo_detail.html'
pk_url_kwarg = 'identifier'

# TODO, need to add logic of flagged items etc. to custom Manager and use that instead
queryset = Foo.objects.filter(is_public=True)

# # FIXME: This is a hack, just to demo
# def get_object(self, queryset=None):
# objs = Foo.objects.filter(identifier=self.request.GET.get('identifier', 0))
# if objs:
# return objs[0]
# else:
# obj = Foo()
# return obj

在 urls.py 中,我有以下语句:

path('foo/view/<str:identifier>/', FooDetailView.as_view(), name='foo-detail'),

为什么 Django 需要一个数字(即使我已经明确指定了一个字符串 - 并且还提供了一个 pk_url_kwarg 参数)?

如何解决这个问题?

最佳答案

pk_url_kwarg 属性仅由 Django 使用来从 View kwargs 中获取正确的 kwarg。最后,Django 仍然会创建一个 queryset.filter(pk=pk) 形式的 filter (其中 pk = self.kwargs.get(self.pk_url_kwarg ))。相反,如果您想对自定义字段执行过滤,您应该设置 slug_url_kwargslug_field:

class FooDetailView(DetailView):
model = Foo
template_name = 'foo_detail.html'
slug_url_kwarg = 'identifier'
slug_field = 'identifier'

# TODO, need to add logic of flagged items etc. to custom Manager and use that instead
queryset = Foo.objects.filter(is_public=True)

关于具有自定义标识符(不是 pk)的 Django DetailView : Field 'id' expected a number but got 'XQ1wfrpiLVAkjAUL' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67821125/

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