Friday, October 28, 2011

Re: Comparing two ManyToMany fields for same entries

Try this:

for friendof0 in Person0.friends.all():
for friendof1 in Person1.friends.all():
if friendof0 == friendof1:
# Person 0 and Person 1 share a friend.
else:
# They have no shared friends.

Brett


On 10/28/11 12:59 PM, "Kevin" <kveroneau@gmail.com> wrote:

>Just thought I'd add another example using Python script:
>
>Person0 = Person()
>Person1 = Person()
>Person2 = Person()
>Person0.friends.add(Person2)
>Person2.friends.add(Person0)
>Person2.friends.add(Person1)
>Person1.friends.add(Person2)
>
>Now, I would like to do the following, but it seems to fail:
>
>Person0.friends.all() in Person1.friends.all(). I would like it to
>say if Person0 and Person1 share another friend in common.
>
>Person0 and Person2 are friends
>Person1 and Person2 are friends
>Person0 and Person1 are NOT friends, but share a friend in common.
>How does one find out that even though Person0 and Person1 are not
>friends, they do share Person2 as a friend.
>
>I can use my eye on a Python shell to see that Person2 exists on both
>Peson0 and Person1, but how does one make the code see it?
>
>Sorry for having to clarify this so much, I'm just not sure that my
>last post actually explained it properly.
>
>Thanks.
>
>On Oct 28, 12:30 pm, Kevin <kveron...@gmail.com> wrote:
>> Hello,
>>
>> I am building a model which shares a relation with another model
>> using a ManyToManyField. What I need to do, is find out which models
>> are on both on two seperate ManyToManyField lists. Here is a simple
>> example of what I am trying to do:
>>
>> Person:
>> friends=ManyToManyField(self)
>>
>> To find out this persons direct friends, Person.friends...
>> To find out which friends this Person shares in common with another
>> Person, ????
>>
>> Person0:
>> Person1
>> Person6
>> Person3
>> Person8
>>
>> Person1:
>> Person2
>> Person6
>>
>> What would be the most optimized QuerySet to find out that both
>> Person0 and Person1 are both friends with Person6?
>>
>> Is there a specific Django app perhaps that can ease develop of this
>> type of data relations between objects?
>>
>> 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.
>

--
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.

No comments:

Post a Comment