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

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
Visit this group at http://groups.google.com/group/django-users?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.


Reply via email to