john
john

Reputation: 2329

django: how to use many-to-many relationships in values()?

i need to group results by a field that requires a few joins from the original model:

// response_filter_args is created dynamically
responses = Response.objects.filter(**response_filter_args) \
        .values('customer__tags__tag') \                  # django doesn't like this
        .annotate(average_score=Avg('rating__score'))

Response -> customer -> tags (many-to-many field pointing to Tag) -> tag (the tag as a string)

Models are:

class Response(models.Model):
    customer = models.ForeignKey(Customer)
    ...

class Customer(models.Model):
    tags = models.ManyToManyField(Tag)
    ...

class Tag(models.Model):
    tag = models.CharField(max_length=255)
    ...

i'm trying to calculate average ratings. to make it work i need to tell django to group by 'tag', but it refuses to. it gives an error:

Invalid field name: 'customer__tags__tag'

anyone know how i can get it to group by tag? i've tried all the combinations of underscores in customer_tags_tag that i can think of, but nothing works.

Upvotes: 0

Views: 4062

Answers (2)

Bernhard Vallant
Bernhard Vallant

Reputation: 50786

I do not think that this will work, since django can't get objects that are related via a ManyToMany-relation with one query.

Upvotes: 0

Marcus Whybrow
Marcus Whybrow

Reputation: 19998

If you check out the Django docs for values() you will see that many to many field support has only been added in the development version and not in 1.2:

The values() method previously [pre dev version] did not return anything for ManyToManyField attributes and would raise an error if you tried to pass this type of field to it.

Upvotes: 3

Related Questions