class Proposal(models.Model):
author = models.ForeignKey(Person, related_name="author")
def get_tags(self):
return Tag.objects.filter(tagged_proposals=self.id)
class Tag(models.Model):
tagged_proposals = models.ManyToManyField(Proposal)
name = models.CharField(primary_key=True, max_length=60)
I need to list the proposal's tags on a certain template so I would write {% for tag in proposal.get_tags %}
and it works perfectly.
Now I read about Managers and it seems a good move to convert my get_tags
into a Manager. I tried the following but it didn't output a thing. What am I doing wrong? Does it make sense to turn it a Manager in the first place?
class ProposalsTagsManager(models.Manager):
def get_query_set(self):
proposal_id = how-do-i-get-the-proposal-id???
return Tag.objects.filter(tagged_proposals=proposal_id)
usage: {% for tag in p.tags.all %}
output: nothing
You don't need a custom function for this.
When a table is being referenced with a ManyToManyField you get a method called MODEL_set to get a queryset of that model.
So in your case you can reference all your tags like this:
proposal = Proposal.objects.get(pk=1)
tags = proposal.tag_set.all() # You can also use filter here