【问题标题】:Right way to create urls using inherit class in Django在 Django 中使用继承类创建 url 的正确方法
【发布时间】:2016-06-06 21:34:48
【问题描述】:

在 Django 中,我有我的应用程序,我在其中放置有关这些国家/地区的国家和城市的信息。这是我的 model.py 文件:

class Country(models.Model):
        class Meta:
                verbose_name_plural = u'Countries'

        name = models.CharField(max_length=50)
        slug = models.CharField(max_length=255)
        description = models.TextField(max_length=10000, blank=True)

        def __unicode__(self):
                return self.name

class City(models.Model):
        class Meta:
                verbose_name_plural = u'Cities'

        name = models.CharField(u'city', max_length=200)
        slug = models.CharField(max_length=255, blank=True)
        description = models.TextField(max_length=10000, blank=True)
        country = models.ForeignKey('Country', blank=True, null=True)

        def __unicode__(self):
                return self.name

我有我的国家的详细视图,在这个视图中有这个国家的城市列表(views.py):

def CountryDetail(request, slug):
        country = get_object_or_404(Country, slug=slug)
        list_cities = City.objects.filter(country=country)
        return render(request, 'country/country.html', {'country':country, 'list_cities':list_cities})

这是我的 urls.py:

url(r'^(?P<slug>[-_\w]+)/$', views.CountryDetail, name='country'),

我想创建一个包含国家名称和城市名称的城市网址,例如domain.com/spain/barcelona/

所以我创建了城市的详细视图,它看起来像这样:

def CityDetail(request, cityslug, countryslug):
        country = Country.objects.get(slug=countryslug)
        country_city = City.objects.get(country=country)
        city = get_object_or_404(country_city, slug=cityslug)
        return render(request, 'country/city.html', {'country':country, 'city':city})

这是我的 urls.py 城市详细信息:

url(r'^(?P<countryslug>[-_\w]+)/(?P<cityslug>[-_\w]+)$', views.CityDetail, name='resort'),

这就是我在链接到城市的国家/地区的 html 文件详细信息中的样子:

<h1>{{country.name}}</h1>
<p>{{country.description}}</p>
<h2>Cities</h2>
{% for city in list_cities %}
   <a href="/{{country.slug}}/{{city.slug}}">
      <p>{{city.name}}</p>
   </a>
{% endfor %}

但是当我点击城市网址的链接时,我得到了错误。 Object is of type 'City', but must be a Django Model, Manager, or QuerySet

在回溯中,我在 views.py 文件中的 CityDetail 函数中看到了该问题: resort = get_object_or_404(country_city, slug=cityslug).

希望你能帮我解决它的问题。谢谢。

【问题讨论】:

    标签: django django-urls


    【解决方案1】:

    是的,您不能在实际的 City 对象上调用 get_object_or_404;您可以查询的是模型或查询集,而不是实例。你认为这个电话会做什么?

    但实际上根本问题在此之前;您对country_city 的定义毫无意义。首先,这仅在当前有效,因为您可能在所查询的国家/地区只有一个城市。当您有多个对象时,该行将因 MultipleObjectsReturned 异常而失败,因为get 只能返回一个对象。

    您应该完全删除该行,并直接从国家/地区查询城市:

    country = Country.objects.get(slug=countryslug)
    city = get_object_or_404(City, country=country, slug=cityslug)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-06
      • 2016-09-23
      • 2020-11-13
      • 2012-06-22
      • 1970-01-01
      • 2021-10-26
      • 2015-12-04
      • 2013-05-25
      相关资源
      最近更新 更多