python - Calling methods from models.py inside views.py without creating instance -


new django coming .net architectural question.

inside models.py, have concept called city. these cities can enabled/disabled.

inside views, want retrieve active cities under view called cities. need retrieve active cities in many places, thought i'd make method inside models.py city class called get_in_country, looks this:

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 

anyway, question is: how use inside views.py?

being awesome noob, of course tried this:

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) 

now, don't have einstein (ahem, jon skeet?) realize go wrong, haven't made instance of city , cause exception:

unbound method get_in_country() must called city instance first argument (got int instance instead) 

so: how modify code use new awesome submethod?

you need define get_in_country static function

by adding decorator

@staticmethod 

just before class defenition as

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

Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -