如何在Django中查询多对多关系
我有一个包含不同组织类型的组织列表。我有一个表,其中包含姓名、电话等信息……然后还有另一个表,其中的 id 固定为组织类型。然后是一个保存多对多关系的表,因为一个组织可以有许多不同的组织类型。
我想要做的是按字母顺序列出属于每种组织类型的所有俱乐部。
我不确定这是否需要在 views.py
中完成,或者是否应该在我的模板文件中完成。
这是我的模型:
class ClubType(models.Model):
name = models.CharField(max_length = 250)
def __unicode__(self):
return self.name
class Club(models.Model):
name = models.CharField(max_length = 250,
verbose_name = "Club or Organization Name",
)
created_date = models.DateTimeField(
auto_now_add = True,
)
updated_date = models.DateTimeField(
auto_now = True,
auto_now_add = True,
)
club_type = models.ManyToManyField(ClubType)
username = models.CharField(max_length = 100,
blank = True, null = True
)
contact_name = models.CharField(max_length = 250,
blank = True, null = True,
)
phone_number = models.CharField(max_length = 250,
blank = True, null = True,
)
def __unicode__(self):
return self.name
class Meta:
ordering = ('name', )
我是 python 和 Django 的菜鸟,所以任何帮助将不胜感激。
谢谢
I have a list of organizations that full under different organization types. I have a table that holds the name, phone, etc... and then another table that has an id fixed to an organization type. Then a table that holds the many to many relationship because an organization can have many different organization types.
What I'm wanting to do is list all the clubs alphabetically that fall under every organizational type.
I'm not sure if this needs to be done in views.py
or if it should be done in my template file.
Here are my models:
class ClubType(models.Model):
name = models.CharField(max_length = 250)
def __unicode__(self):
return self.name
class Club(models.Model):
name = models.CharField(max_length = 250,
verbose_name = "Club or Organization Name",
)
created_date = models.DateTimeField(
auto_now_add = True,
)
updated_date = models.DateTimeField(
auto_now = True,
auto_now_add = True,
)
club_type = models.ManyToManyField(ClubType)
username = models.CharField(max_length = 100,
blank = True, null = True
)
contact_name = models.CharField(max_length = 250,
blank = True, null = True,
)
phone_number = models.CharField(max_length = 250,
blank = True, null = True,
)
def __unicode__(self):
return self.name
class Meta:
ordering = ('name', )
I'm a noob to python and Django so any help would be greatly appreciated.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
基本上,您需要执行以下步骤:
有很多方法可以实现这一点,我不建议将此逻辑放入模板中,因为简单的事实是,表达其背后的逻辑可能更容易视图(或在自定义管理器如果你得到 最后
一个例子(警告:未经测试的代码):
你剩下的是一个俱乐部类型列表的列表,每个列表都按名称排序,其形式如下:
Basically you need to do the following steps:
There are many ways to achieve this, and I would not recommend putting this logic into the template for the simple fact that expressing the logic behind it is probably easier in the view (or in a custom Manager if you get adventurous later in your Django life)
An example (warning: untested code):
What you are left with in the end is a list of club type lists, each sorted by name that is of the form: