help with ManyToMany

62 views
Skip to first unread message

dave.l

unread,
Jan 27, 2016, 10:50:21 AM1/27/16
to Django users
Hi,

I have recently returned to a Django project after a few years and I'm a little rusty on ManyToMany fields.

Here's my very simple models:


class Studio(models.Model):
    name
= models.CharField(max_length=255, unique=True)

class StudioGroup(models.Model):
    description
= models.CharField(max_length=255, unique=True)
    studio
= models.ManyToManyField(Studio)


So a bunch of Studio(), which can be in multiple StudioGroups()

Given a single instance of a Studio(), I would like a single list of all other studios in all other groups.

so if Group1 is A,B,C and Group2 is A,D,E

I would like to return B,C,D,E for A.

My current solution is entirely in Python (which works), but I'd like a more Django-esque solultion of possible!

Thank you,

Xristos Xristoou

unread,
Jan 27, 2016, 3:36:26 PM1/27/16
to Django users
your code is correct,where are the problem ?in the admin first add Studio and sfter this select on the field studio from class studiogroup one or more entries from the class studio so simple,

christos

dave.l

unread,
Jan 28, 2016, 4:16:21 AM1/28/16
to Django users
Hi,

I am happy with my models, and I'm fine inserting data, what I would like help with is retrieval.

given a single instance of a Studio() I can get studio.studiogroup_set.all() which I can then iterate to find the individual studios and build my resulting list ensuring no duplicates and not 'studio' itself. All this is working in Python:

choice = self.get_object()
others = []
for set in getattr(choice, "%s_set" % choice.groupname.lower()).all():
    for other in getattr(set, choice.view_name()).exclude(pk=choice.pk):
        if other not in others:
            others.append(other)
for other in others:
    print other

but this doesn't seem very elegant and I'm wondering if there's a more 'django' way of doing this.

Peter of the Norse

unread,
Feb 1, 2016, 1:49:31 AM2/1/16
to django...@googlegroups.com
I hope you forgive me skipping all of that getattr nonsense.

others = Studio.objects.filter(studio_group__in = choice.studio_group_set.all()).exclude(pk=choice.pk)

-- 
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 django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/7512817d-d348-48b2-abf1-f3f584650cce%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Peter of the Norse



dave.l

unread,
Feb 2, 2016, 5:42:15 PM2/2/16
to Django users
Hi Peter,

Thank you -- that's perfect!
Reply all
Reply to author
Forward
0 new messages