[Answer]-Django-tables2 ignores ManyToManyField

0👍

Looks like this is bug in django-tables2 when using with django 1.7:
https://github.com/bradleyayers/django-tables2/issues/211

2👍

Do this:

class ItemTable(tables.Table):
    class Meta:
        model = Item
        attrs = {"class": "paleblue"}
        fields = ("uuid", "name", "brand", "categories")

    categories = tables.Column()

    def render_categories(self, value):
        if value is not None:
            return ', '.join([category.name for category in value.all()])
        return '-'
👤ruddra

0👍

It looks like it hasn’t been merged in. As a work around you can do a render with a record and iterate the same way.

ie.

 def render_categories(self, record):
        if record.category is not None:
            return ', '.join([category.name for category in record.category.all()])
        return '-'
👤Craig

0👍

Maybe is not the cleaner option but this worked for me:

class Item(models.Model):
    name = models.CharField(max_length=255)
    uuid = models.CharField(max_length=36)
    categories = models.ManyToManyField(Category, null=True)
    brand = models.ForeignKey(Brand)

   @property
   def categories_str(self):
       return ', '.join([category.name for category in value.all()])


class ItemTable(tables.Table):
    categories = tables.Column(accessor='categories_str')

    class Meta:
        model = Item
        attrs = {"class": "paleblue"}
        fields = ("uuid", "name", "brand", "categories")

-1👍

Do This:

class ItemTable(tables.Table):
    class Meta:
        model = Item
        attrs = {"class": "paleblue"}
        fields = ("uuid", "name", "brand", "categories")

    categories = tables.Column(empty_values=())

    def render_categories(self, record):
        if record.categories.all():
            return ', '.join([category.name for category in record.categories.all()])
        return '-'

Note that empty_values=() is important to be written in tables.Column()

Leave a comment