【问题标题】:Calling methods from models.py inside views.py without creating instance从views.py中的models.py调用方法而不创建实例
【发布时间】: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


【解决方案1】:

您需要将get_in_country 定义为static function

通过添加装饰器

@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):

【讨论】:

  • 啊,静态方法。我在 .NET 中总是避免使用的方法;-) 在执行静态方法时,我假设您删除了“self”?如果没有,你自己提供什么?
  • 您需要提供任何self 作为参数。如果您需要访问某些类变量,请改为传递实例
  • 但是假设我的新静态方法是 'def get_in_country(self, country_id):',我通过说 City.get_in_country(current_country.id) 来调用它 - 我会得到一个 "get_in_country()正好需要 2 个参数(1 个给定)”错误。如何解决这个问题?
  • @LarsHoldgaard 不,你应该完全失去self。那就是 def 必须看起来像 def get_in_country(country_id):。例如ideone.com/wLA3g8
  • 太棒了!非常感谢 - 这是有道理的! :) 真的很有帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-11-22
  • 1970-01-01
  • 2016-06-12
  • 1970-01-01
  • 2021-08-28
  • 2012-07-23
  • 2018-07-27
相关资源
最近更新 更多