How to query a many to many relationship in 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 becaus开发者_开发知识库e 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
Basically you need to do the following steps:
- Get the distinct club types
- For each club type, select the clubs that include that type (also see this)
- Sort the selection from #2 alphabetically
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):
# step 1
club_types = ClubTypes.objects.distinct()
# step 2 & #3
club_sets = []
for current_club_type in club_types:
cset = Clubs.objects.filter(club_type__id=current_club_type.pk).order_by('name')
club_sets.append((current_club_type, cset))
What you are left with in the end is a list of club type lists, each sorted by name that is of the form:
[ (clubtype1, [ club1, club2, ...]), (clubtype2, [ club2, club8, ...]), ... ]
精彩评论