1

来自 .NET 的 Django 新手,有一个架构问题。

在我的里面models.py,我有一个概念叫city。这些城市可以启用/禁用。

在我的视图中,我想检索我视图下的所有活动城市,称为Cities. 我需要在很多地方检索所有活跃的城市,所以我想我会在我的models.py城市类中创建一个名为的方法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)

现在,您不必成为爱因斯坦(咳咳,Jon Skeet?)就可以意识到这会出错,因为我没有创建 City 的实例并且会导致异常:

unbound method get_in_country() must be called with City instance as first argument (got int instance instead)

那么:您将如何修改我的代码以使用我新的超赞子方法?

4

1 回答 1

1

您需要定义get_in_country静态函数

通过添加装饰器

@staticmethod

就在阶级辩护之前

@staticmethod 
    def get_in_country(self, country_id):

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

    @staticmethod # Changed here
    def get_in_country(self, country_id):
于 2015-05-15T05:43:08.713 回答