【发布时间】:2015-07-26 22:48:44
【问题描述】:
来自 .NET 的 Django 新手,有一个架构问题。
在我的models.py 中,我有一个名为city 的概念。可以启用/禁用这些城市。
在我的视图中,我想检索我的视图下名为Cities 的所有活跃城市。我需要在很多地方检索所有活跃的城市,所以我想我会在我的models.py city 类中创建一个名为get_in_country 的方法,所以它看起来像这样:
class City(models.Model):
title = models.CharField(max_length=200)
alias = models.CharField(max_length=200)
country = models.ForeignKey(Country, null=True)
is_visible = models.BooleanField(default=False)
def __str__(self):
return self.title
def get_in_country(self, country_id):
#return best code ever seen
无论如何,我现在的问题是:如何在 views.py 中使用它?
作为一个很棒的菜鸟,我当然试过这个:
def country(request, alias):
cities_in_country = City.get_in_country(1) #whatever id
data = {
'cities_in_country': cities_in_country,
}
return render(request, 'country.html', data)
现在,您不必成为 Einstein(咳咳,Jon Skeet?)就会意识到这会出错,因为我没有创建 City 的实例并且会导致异常:
unbound method get_in_country() must be called with City instance as first argument (got int instance instead)
那么:您将如何修改我的代码以使用我新的超赞子方法?
【问题讨论】:
-
由于您想按国家/地区过滤 City 表中的所有行,因此最好使用像
City.objects.filter_by_country(country)这样的自定义 Manager 方法。
标签: python django django-models django-1.8