I've got two models, say "Foo" and "Bar"
"Bar" establishes a manyToManyField relationship with "Foo":
foos = models.ManyToManyField(Foo,
filter_interface=models.HORIZONTAL, null=True, blank=True)
I'm using a generic detail template for Foo, and want to include the
matching Bars.
Since Bar has the mtm and Foo doesn't, I figured Bar was aware of Foo,
but not the other way around, and therefore I would need a template
tag.
So assuming my logic so far is OK, how should I get the correct Bar
objects (the ones that have a matching Foo in foos)?
I think to access it in the template, you'd just need to pass the
information from your view?
On Jun 6, 1:42 pm, "bax...@gretschpages.com" <mail.bax...@gmail.com>
wrote:
On Jun 6, 4:05 pm, "chinka...@gmail.com" <chinka...@gmail.com> wrote:
> This doesn't exactly answer your question (because I'm a huge noob
> still), but M2M relationships work in both directions:http://www.djangoproject.com/documentation/db-api/#many-to-many-relat...
Based on what you've said so far, you shouldn't need to write a new
view. You just need to reference the m2m data correctly. Assuming you
have the models:
class Foo(models.Model):
name = models.CharField()
class Bar(models.Model):
name = models.CharField()
foos = models.ManyToManyField(Foo)
Then you can, in view code, ask for:
>>> Foo.objects.all()
>>> Bar.objects.all()
>>> mybar.foos.all()
>>> myfoo.bar_set.all()
And in template, if you have mybar and myfoo into the context, you can write:
{{ mybar }}
{{ myfoo }}
{% for foo in mybar.foos.all %}
{{ foo.name }}
{% endfor %}
{% for bar in myfoo.bar_set.all }
{{ bar.name }}
{% endfor %}
Yours,
Russ Magee %-)
I went ahead and created a custom view for Foo, so that's taken care
of, but Bar (which should be easy) isn't working either.
I have:
class Bar(models.Model):
name= models.CharField(maxlength=100)
foos = models.ManyToManyField(Foo,
filter_interface=models.HORIZONTAL, related_name="foos", null=True,
blank=True)
slug = models.SlugField(prepopulate_from=('name',))
In passing it in a generic view, in the template, shouldn't I just be
able to do this?
{% for foo in bar.foos_set.all %}
test
{% endfor %}
I get nothing. If I put in {{ bar.foos_set.all }} I get an object
pointer, not a list.
I haven't thrown any errors when I ran syncdb or validate.
On Jun 7, 8:58 am, "Russell Keith-Magee" <freakboy3...@gmail.com>
wrote:
On Jun 7, 12:09 pm, "bax...@gretschpages.com" <mail.bax...@gmail.com>
wrote:
This would all be a lot clearer if you would read the DB-api docs. The
related-objects section explains this aspect of Django in great
detail.
http://www.djangoproject.com/documentation/db-api/#related-objects
In short:
Your Bar model has a foos attribute. Therefore, bar.foos.all().
Your Foo model has an implied attribute, because it is on the
receiving end of a m2m relation with Bar. Therefore,
foo.bar_set.all().
Yours,
Russ Magee %-)
On Jun 7, 7:09 pm, "Russell Keith-Magee" <freakboy3...@gmail.com>
wrote: