Hulk
Hulk

Reputation: 34170

Querying many to many fields in django

In the models there is a many to many fields as,

from emp.models import Name

  def info(request):
     name = models.ManyToManyField(Name)

And in emp.models the schema is as

 class Name(models.Model):
      name = models.CharField(max_length=512)


      def __unicode__(self):
          return self.name

Now when i want to query a particular id say for ex:

         info=  info.objects.filter(id=a)
         for i in info:
              logging.debug(i.name) //gives an error 

how should the query be to get the name

Thanks..

Upvotes: 0

Views: 920

Answers (2)

Casey W. Stark
Casey W. Stark

Reputation: 757

Lukasz is right, but just so you know, it doesn't make sense to filter on an id unless you use info.object.filet(id__in=a) and a is a list of some sort. If you filter on a single id, you should be using objects.get(**kwargs) first of all, and it will return that specific Info instance instead of a QuerySet.

Upvotes: 1

Łukasz
Łukasz

Reputation: 36201

info.name is ManyToManyField so if you want all Name objects associated with it you have to use .all() method on it. Only then you'll get list (queryset) of Name objects:

info_list = info.objects.filter(id=a)
for info_object in info_list:
    for name_object in info_object.name.all():
        print name_object.name

Upvotes: 3

Related Questions