fox
fox

Reputation: 16506

How to permit editing of a many-to-many relationship in the django admin panel

Have a class definition that looks something like this

class someClass(models.Model):
    field1 = models.ForeignKey('other_app.field4')
    field2 = models.ManyToManyField('other_app.field5')
    variable_name  = [1-char choices]
    field3 = models.CharField(max_length=1, choices=variable_name, blank=True)

When I try to edit this class in the admin panel, I get:

TypeError at /admin/[app]/[someClass]/add/

Assume it has to do with the ManytoMany field, any obvious workarounds?


UPDATE: Ok, so I figured out the issue: the code that my partner had written had an iterative __str__ function:

def __str__(self):
    str_rep = '%s for ' % (self.field1)
    for p in self.field2:
        str_rep += str(p) + self.field3

Any ideas on how to rewrite this?

Upvotes: 0

Views: 223

Answers (1)

In the future, try posting an actual traceback and the relevant lines of code. It would have shown us exactly where this code was breaking.

field2 is not iterable. You need to get a QuerySet from your ManyRelatedManager by calling all() or filter(...).

https://docs.djangoproject.com/en/dev/topics/db/queries/#many-to-many-relationships

def __str__(self):
    str_rep = '%s for ' % (self.field1)
    for p in self.field2.all():
        str_rep += str(p) + self.field3

Upvotes: 1

Related Questions