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

问题描述 投票:0回答:3

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

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

My models

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

My Views

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

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

My Urls

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

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

# etc. etc.
python django django-models django-views django-urls
3个回答
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)

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


2
投票

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

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

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


1
投票

从qazxsw poi获得qazxsw poi。对于qazxsw poi,您需要返回country_id而不是单个对象。所以使用kwargs而不是get_queryset

queryset
© www.soinside.com 2019 - 2024. All rights reserved.