声明的顺序在models.py(Django / Python)中是否重要? [英] Does order of declaration matter in models.py (Django / Python)?

查看:79
本文介绍了声明的顺序在models.py(Django / Python)中是否重要?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

models.py

I have something like this in models.py

class ZipCode(models.Model):
    zip = models.CharField(max_length=20)
    cities = City.objects.filter(zip=self).distinct()

class City(models.Model):
    name = models.CharField(max_length=50)
    slug = models.CharField(max_length=50)
    state = models.ForeignKey(State)
    zip = models.ManyToManyField(ZipCode)

当我这样做时,我得到:

When I do this I get:

NameError: name 'City' is not defined

这是因为顺序声明有关系吗?如果是这样,我该怎么做,因为无论哪种方式安排它,看来我都会收到NameError。

Is this because the order of declaration matters? And if so, how can I do this, because either way I arrange this, it looks like I'm going to get a NameError.

谢谢。

推荐答案

是的,顺序确实很重要。

Yes order does matter as others have noted.

但是,遇到此问题几乎总是表明您做错了事。

Though, encountering this issue is almost always going to be an indication that you're doing something wrong.

在这种情况下,您的声明:

In this case your declaration:

cities = City.objects.filter(zip=self).distinct()

...都是多余和不好的做法。您可以通过在视图中引用该邮政编码的city_set来查找与该邮政编码相关的城市(即,不在您的模型中!)。因此,如果zip是ZipCode的实例,则可以执行以下操作:

... is both redundant and bad practice. You can find the cities related to a zip code by referring to that zip code's city_set in your views (ie not in your model!). So if zip is an instance of ZipCode, you would do:

cities = zip.city_set.all()

如果您真的想将其称为城市而不是 city_set,则可以在m2m声明中使用related_name参数。

If you really want to call it 'cities' rather than 'city_set' you can use the related_name parameter in your m2m declaration.

这篇关于声明的顺序在models.py(Django / Python)中是否重要?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆