New to Django coming from .NET with an architectural question.
Inside my models.py, I have a concept called city. These cities can be enabled/disabled.
Inside my views, I want to retrieve all active cities under my view called Cities. I need to retrieve all active cities in many places, so I thought I'd make a method inside my models.py city class called get_in_country, so it looks like 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, my question now is: how do I use this inside views.py?
Being an awesome noob, I 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, you don't have to be Einstein (ahem, Jon Skeet?) to realize this will go wrong, as I haven't made an instance of City and will cause an exception:
unbound method get_in_country() must be called with City instance as first argument (got int instance instead)
So: how would you modify my code to use my new awesome submethod?
City.objects.filter_by_country(country)would be best pratice.