Search code examples
djangodjango-tables2m2m

django tables 2 accessing m2m


I have two models:

class Hi(models.Model):
   name = models.CharField(max_length=2)


class Hello(models.Model):
    name = models.CharField(max_length=50)
    his = models.ManyToManyField(Hi)

I am trying to render Hello model. Thus I have tables.py like this:

class HelloTable(tables.Table):
    his = models.ColoumnField()

    def render_his(self, value):
        hi = []
        for i in value.his.all():
            hi.append(i)
        return (',').join(hi)

     #And the metas

I get ManyToMany has no attribute his. What's wrong?


Solution

  • this should solve your issue and simplify your code a little bit:

    def render_his(self, value):
        return (', ').join(list(value.all()))
    

    or

    def render_his(self, value):
        return (', ').join([x.name for x in value.all()])
    

    if you want a specific attribute instead of the unicode representation of your Hi objects.

    You are getting the error because value is a ManyToManyField instance, not a Hello instance.