简体   繁体   中英

What's the straightforward way to implement one to many editing in list_editable in django admin?

Given the following models:

class Store(models.Model):
    name = models.CharField(max_length=150)

class ItemGroup(models.Model):
    group = models.CharField(max_length=100)
    code = models.CharField(max_length=20)

class ItemType(models.Model):
    store = models.ForeignKey(Store, on_delete=models.CASCADE, related_name="item_types")
    item_group = models.ForeignKey(ItemGroup)
    type = models.CharField(max_length=100)

Inline's handle adding multiple item_types to a Store nicely when viewing a single Store .

The content admin team would like to be able to edit stores and their types in bulk. Is there a simple way to implement Store.item_types in list_editable which also allows adding new records, similar to horizontal_filter ? If not, is there a straightforward guide that shows how to implement a custom list_editable template? I've been Googling but haven't been able to come up with anything.

Also, if there is a simpler or better way to set up these models that would make this easier to implement, feel free to comment.

How about making ItemType a ManyToManyField for Store?

To me it seems logical that if you're changing the ItemTypes available in a Store, you're changing a property of the Store (not the ItemType).

eg:

from django.db import models

class ItemGroup(models.Model):
    group = models.CharField(max_length=100)
    code = models.CharField(max_length=20)

class ItemType(models.Model):
    item_group = models.ForeignKey(ItemGroup)
    type = models.CharField(max_length=100)

class Store(models.Model):
    name = models.CharField(max_length=150)
    item_type = models.ManyToManyField(ItemType, related_name="store")

# admin
from django.contrib import admin

class StoreAdmin(admin.ModelAdmin):
    list_display=('name', 'item_type',)
    list_editable=('item_type',)

for model in [(Store, StoreAdmin), (ItemGroup,), (ItemType,)]:
    admin.site.register(*model)

I get an error here:

File "C:\Python27\lib\site-packages\django\contrib\admin\validation.py", line 43, in validate
% (cls.__name__, idx, field))
django.core.exceptions.ImproperlyConfigured: 'StoreAdmin.list_display[1]', 'item_type' is a ManyToManyField which is not supported.

Which I solved by commenting out lines 41-43 in django.contrib.admin.validation:

#if isinstance(f, models.ManyToManyField):
#    raise ImproperlyConfigured("'%s.list_display[%d]', '%s' is a ManyToManyField which is not supported."
#        % (cls.__name__, idx, field))

Probably not the ideal solution, but it seemed to work for me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM