how to get ManyToMany relations?

3 views
Skip to first unread message

Benjamin W.

unread,
Dec 27, 2009, 11:37:51 AM12/27/09
to Django users
Hi there,

I've problems to access manyToMany relartions.
I got the following model:

class ModelType(models.Model):
description = models.CharField(max_length=100)
def __unicode__(self):
return u"%s" % (self.description)

class CarModel(models.Model):
description = models.CharField(max_length=100)
order = models.IntegerField(null=True)
modelTypes = models.ManyToManyField(ModelType)
def __unicode__(self):
return u"%s" % (self.description)

Now I want the ModelTypes for a specfic CarModel.
I thougt it should be something like this:

model = CarModel.objects.filter(pk = modelId)
for m in model.modelTypes.all():
data = data+m.description+'|'

But I get this error:
QuerySet object has no attribute modelType.

Thanks for your help!

Michael Jenkinson

unread,
Dec 27, 2009, 3:25:17 PM12/27/09
to django...@googlegroups.com
hi

there isnt a many to many relationship here, its down the 'is a ... has a' bit of OO

one manufacturer makes (one car design that has a number of (models with a set of features))


class manufacturer
{
list of designs(cardesign)
}

class cardesign
{
list of models(model)
}


class model
{
list of features
}

cheers


michael

Hi there,

Thanks for your help!

--

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



akaariai

unread,
Dec 27, 2009, 3:32:31 PM12/27/09
to Django users

> model = CarModel.objects.filter(pk = modelId)
> for m in model.modelTypes.all():
>         data = data+m.description+'|'

Your problem is that objects.filter(pk=modelId) gives you a list of
one element. You need to use either objects.get(pk=modelId) or
objects.filter(pk=modelId)[0].

Reply all
Reply to author
Forward
0 new messages