Thursday, January 28, 2016

Re: help with ManyToMany

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.

On Wednesday, January 27, 2016 at 8:36:26 PM UTC, Xristos Xristoou wrote:
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

Τη Τετάρτη, 27 Ιανουαρίου 2016 - 5:50:21 μ.μ. UTC+2, ο χρήστης dave.l έγραψε:
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,

--
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+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@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.

No comments:

Post a Comment