fabio
fabio

Reputation: 1365

Django admin list_display model method

I have this model.py:

class Topping(models.Model):
    name = models.CharField(max_length=32)

    def __str__(self):
        return self.name

class Base(models.Model):
    name = models.CharField(max_length=32)
    slug = models.SlugField(primary_key=True)


class Advanced(models.Model):
    toppings = models.ManyToManyField(Topping)


class Mymodel(Base, Advanced):
    ...

    def toppings_list(self):
        list_top = Advanced.toppings
        return list_top

I want to show the list of toppings (preferably formatted, so a list only of the field name of the Topping model) in my Admin, so:

class MymodelAdmin(admin.ModelAdmin):
    #list_display = (..., model.Mymodel.toppings_list(), ...) #Error: missing 1 required positional argument: 'self'
    #list_display = (..., model.Mymodel.toppings_list(self), ...) #Error: self is not definited
    list_display = (..., model.Mymodel.toppings_list, ...) #Gibberish: <django.db.models.fields.related_descriptors.ManyToManyDescriptor object at 0x0387FFD0>

Only the last one works but don't gives nothing useful.

I tried these too (I want format the list before to display):

class MymodelAdmin(admin.ModelAdmin):
    mylist=model.Mymodel.toppings_list #I don't change nothing for now
    #mylist=[t for t in model.Mymodel.toppings_list] #Error: 'function' object is not iterable
    list_display = ('mylist') #core.Topping.None

again, the last one works but don't gives nothing useful (also Topping isn't None)

Thank you

Upvotes: 0

Views: 2315

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599956

You just use the name of the method, as a string.

list_display = ("toppings_list", ...)

Note however that your toppings_list method itself makes absolutely no sense. You need to return the toppings that are related to the current object, not a field object, and you need to format then as a string.

def toppings_list(self):
    return ", ".join(self.toppings.values_list("name", flat=True))

Upvotes: 3

Related Questions