On Thu, Apr 11, 2013 at 3:42 PM, Matthieu Bouron
<
matthie...@gmail.com> wrote:
> Hello,
>
> Is there a way to handle many-to-many relationship with raw sql queries ?
> I have the following model:
>
> from django.db import models
>
> class Tag(models.Model):
> name = models.CharField(max_length=512, unique=True)
>
> class Bookmark(models.Model):
> link = models.CharField(max_length=512)
> title = models.CharField(max_length=512)
> tags = models.ManyToManyField(Tag)
> added_at = models.DateField()
>
> Using Bookmark.objetcs.all() will result in a subquery for each row of the
> bookmark table which is not acceptable for performance reasons.
> First question is there a way to fetch all the content with a single query ?
> Second question is it possible to use raw sql queries. I tried the
> following:
>
> bookmarks = Bookmark.objects.raw(
> 'SELECT * FROM bookmarkmanager_bookmark b '
> 'LEFT JOIN bookmarkmanager_bookmark_tags bt ON (
b.id =
> bt.bookmark_id) '
> 'LEFT JOIN bookmarkmanager_tag t ON (bt.tag_id =
t.id)'
> )
>
> But when i tried to access the tags attribute on a bookmark i get the
> following exception:
>
> ValueError: "<Bookmark: Bookmark object>" needs to have a value for field
> "bookmark" before this many-to-many relationship can be used.
>
> Thanks in advance,
> Matthieu
>
Are you tied to raw SQL queries? Django itself supports traversing M2M
relationships in a sane manner if you tell it to do so:
https://docs.djangoproject.com/en/1.5/ref/models/querysets/#prefetch-related
Cheers
Tom