[Fwd: Re: how to get ManyToMany relations?]

1 view
Skip to first unread message

Steve Holden

unread,
Dec 27, 2009, 11:44:55 AM12/27/09
to django...@googlegroups.com
Benjamin W. wrote:
> 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)

This statement returns a QuerySet, but in order to use the fields of
CarModel surely you want a CarModel instance.

Therefore you should use

model = CarModel.objects.get(pk=modelId)

(It's better Python style to write the keyword arguments with no spaces
around the "=", reserving the space-delimited form for assignments).

> 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!

The error message was trying to be helpful - you just didn't realize
that you don't need a QuerySet, but a model instance.

regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
PyCon is coming! Atlanta, Feb 2010 http://us.pycon.org/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS: http://holdenweb.eventbrite.com/


Reply all
Reply to author
Forward
0 new messages