Wednesday, June 2, 2010

Getting Duplicate records with Q query

Hi;

Goal is to get a list of notes that include all those created or
addressed to the current user, within the last few days.

Model is a Note, with a created_by field and a many-to-many to a
recipients table which is itself linked to a User Profile table which
is linked to Users.

Note <--Recipients-->UserProfile-->User

This is the query:

 mynotes = Note.objects.filter((Q(recipient__user=id) | Q(created_by =
id)) & Q(target_date__gte=sqlyr))
#.select_related().order_by('-id').distinct()

In the resulting selection, I am getting duplicate records.

If I grab the generated sql, (and with some clean up) I also get duplicates:

SELECT * FROM `intranet_note`
LEFT OUTER JOIN `intranet_noterecipient`
ON (`intranet_note`.`id` = `intranet_noterecipient`.`note_id`)
    LEFT OUTER JOIN `intranet_userprofile`
     ON (`intranet_noterecipient`.`userprofile_id` =
`intranet_userprofile`.`id`)
  WHERE ((`intranet_userprofile`.`user_id` = 6) OR
(`intranet_note`.`created_by_id` = 6 )
   AND `intranet_note`.`target_date` >= 2010-05-30 )

 Now, the duplicates are in fact records that are both created by and
are addressed to the current user.

But later, I have a simple search criteria that looks in both the
subject and body of the note for the same value. That query doesn't
return duplicates even if a note has the same value in both fields.

notes = Note.objects.filter( Q(subject__icontains=q) | Q(body__icontains=q))

So, obviously, my sql is failing me. Would anyone care to take a
minute and explain why this is an expected result?

Thanks.

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

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home


Real Estate