【问题标题】:get_queryset() missing 1 required positional argument: 'country_id'get_queryset() 缺少 1 个必需的位置参数:'country_id'
【发布时间】:2019-07-15 10:28:54
【问题描述】:

例如,我有一个国家/地区列表,他们都有自己的网址 www.example.com/al/。但是当我想过滤每个 country_id 的视图时,它给了我这个错误:

get_queryset() 缺少 1 个必需的位置参数:'country_id'

我的模型

class Country(models.Model):
    COUNTRY_CHOICES = (
        ('Albania', 'Albania'),
        ('Andorra', 'Andorra'),
        # etc. etc.
)
name = models.CharField(max_length=255, choices=COUNTRY_CHOICES, default='Netherlands')

    def __str__(self):
       return self.name

class City(models.Model):
     country = models.ForeignKey(Country, on_delete=models.CASCADE)
     name = models.CharField(max_length=250)

     def __str__(self):
        return self.name

我的观点

class CityOverview(generic.ListView):
template_name = 'mytemplate.html'

def get_queryset(self, country_id, *args, **kwargs):
    return City.objects.get(pk=country_id)

我的网址

# Albania
path('al', views.CityOverview.as_view(), name='al'),

# Andorra
path('ad', views.CityOverview.as_view(), name='ad'),

# etc. etc.

【问题讨论】:

  • 不是您编写 URL 模式的方式。这也不是您编写get_queryset 方法的方式。

标签: python django django-models django-views django-urls


【解决方案1】:

你需要改变几个地方,让我们从模型开始:

class Country(models.Model):
    COUNTRY_CHOICES = (
        ('al', 'Albania'),  # changing the first value of the touple to country code, which will be stored in DB
        ('an', 'Andorra'),
        # etc. etc.
)
    name = models.CharField(max_length=255, choices=COUNTRY_CHOICES, default='nl')

    def __str__(self):
       return self.name

现在,我们需要更新url路径来获取国家代码的值:

 path('<str:country_id>/', views.CityOverview.as_view(), name='city'),

这里我们使用str:country_id,作为一个动态路径变量,它将接受路径中的字符串,该字符串将作为country_id传递给视图。这意味着,无论您何时使用例如localhost:8000/al/,它都会将值al 作为国家代码传递给视图。

最后,在ListView中获取country_id的值,并在queryset中使用。你可以这样做:

class CityOverview(generic.ListView):
    template_name = 'mytemplate.html'

    def get_queryset(self, *args, **kwargs):
        country_id = self.kwargs.get('country_id')
        return City.objects.filter(country__name=country_id)

您需要确保从get_queryset 方法返回queryset,而不是object

【讨论】:

    【解决方案2】:

    发生这种情况是因为您的urls.py 没有通过views.py 位置参数country_id。你可以像这样修复它:

    path('<str:country_id>', views.CityOverview.as_view())
    

    现在,如果用户同时导航到 /al 和 /ad,则此路径将起作用,并且字符串将作为位置参数传递给您的 CityOverview 视图。有关详细信息,请参阅 URL Dispatcher 上的 Django Docs

    【讨论】:

    • 您需要将此与谢尔盖的回答结合起来。
    【解决方案3】:

    只需从kwargs 获取country_id。对于get_queryset,您需要返回queryset,但不能返回单个对象。所以使用filter 而不是get

    def get_queryset(self, *args, **kwargs):
        country_id = self.kwargs['country_id']
        return City.objects.filter(country=country_id)
    

    【讨论】:

      猜你喜欢
      • 2018-12-12
      • 1970-01-01
      • 2018-05-10
      • 2014-09-13
      • 1970-01-01
      • 1970-01-01
      • 2019-10-10
      • 2017-03-27
      相关资源
      最近更新 更多