On Jan 28, 2:33 pm, Odd <[email protected]> wrote:
> I have two models, model1 and model2, where model1 has a ForeignKey
> reference to model2.
>
> Given a list of model1 objects, I need to determine which of these are
> used as a foreign key by a model2 object, and return that list. This
> is my current effort:
>
> returnList=[]
> for model1 in modelList:
>         model2List=model1.model2_set.distinct()
>         if len(model2List) !=0:
>             returnList.append(model1)
> return returnList
>
> There are quite many model2 objects in my database, so this approach
> is rather slow. I'm guessing there is a more clever way to solve my
> problem, but I'm quite new to both django and python. Can anybody
> please give me a hint of a better solution?
>
> Thanks!
>
> Odd-R.

Your code doesn't match the description. You originally say the model1
has a foreign key to model2 - I interpret that to mean that the
ForeignKey is defined on model1. However, your code references
model1.model2_set - which would imply that the FK is defined on
model2, pointing to model1. So, do you want the objects that are
pointed to by FKs from objects in the initial list, or the ones that
FKs in the initial list point to?

In any case, you want something along the lines of:

return_list = Model1.objects.filter(model2__in=model2_list)
--
DR.

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

Reply via email to