Thursday, April 18, 2013

Re: models.ManyToManyField

The first solution works like this:
If you create a foreign key from ModelA to ModelB, Django automatically create something like B.modela_set that works just like the objects attribute, but just for the A objects that are related to B, right?
That's why you can du stuff like attore.film_set.all() to get all the films the actor was in. Django creates film_set for you in Attore instances because you have a ForeignKey from Film to Attore

So, if you wanna list all the films for each actor, something like

actors_dict = dict()
actors = Attore.objects.all()
for actor in actors:
  full_name = '{} {}'.format(actor.nome, actor.cognome)
  actors_list[actor.cognome] = [film.titolo for film in actor.film_set.all()]

Then actors_list would be a dictionary like:
{
  'Nicholas Cage': ['Gone in 60 Seconds', 'Face Off'],
  'Jack Nicholson': ['Batman', 'The Shining']
}


There are different ways of doing this, and I get the feeling you'd like something with templates. But this is pretty much the gist of it.

- Gabe


On Thu, Apr 18, 2013 at 5:44 AM, Federico Erbea <kyuby1988@gmail.com> wrote:
I think it is the first solution that you have proposed, but I can't figure out how to use it. Also, is there a way to make sure that the ID is automatically taken? With a proper publisher for loop I would like all the lists of movies for each actor.

This is my urls.py

from django.conf.urls.defaults import *

urlpatterns = patterns('',    
    (r'^Film$', 'Database.views.film'),
)

and this is my views.py

from django.shortcuts import render_to_response
from django.template import RequestContext
from models import *

def film(request):
    film = Film.objects.all()
    return render_to_response('Film.html', { 'film': film, })

Thanks for the help.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.
 
 

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.
 
 

No comments:

Post a Comment