0

我有以下型号

class tags(models.Model):
    tag = models.CharField(max_length=15) # Tag name
    tagDescription = models.TextField()   # Tag Description
    tagSlug = models.TextField()          # Extra info can be added to the existing tag using this field

class stores(models.Model):
    storeName = models.CharField(max_length=15)                                          # Store Name
    storeDescription = models.TextField()                                                # Store Description
    storeURL = models.URLField()                                                         # Store URL
    storePopularityNumber = models.IntegerField(max_length=1)                            # Store Popularity Number
    storeImage = models.ImageField(upload_to=storeImageDir)                              # Store Image 
    storeSlug = models.TextField()                                                       # This is the text you see in the URL
    createdAt = models.DateTimeField()                                                   # Time at which store is created
    updatedAt = models.DateTimeField()                                                   # Time at which store is updated
    storeTags = models.ManyToManyField(tags)

class tagsAdmin(admin.ModelAdmin):
    list_display = ('tag', 'tagDescription', 'tagSlug')

class storesAdmin(admin.ModelAdmin):
    list_display = ('storeName','storeDescription','storeURL',
                    'storePopularityNumber','storeImage',
                    'storeSlug','createdAt','createdAt','storeTags'
                    )

admin.site.register(tags,tagsAdmin)
admin.site.register(stores,storesAdmin)

每当我尝试运行命令时:python manage.py syncdb 我收到错误:django.core.exceptions.ImproperlyConfigured: 'storesAdmin.list_display[8]', 'storeTags' is a ManyToManyField which is not supported.

我不明白我在这里做错了什么。我想简单地显示 django 管理站点中的所有模型。

4

2 回答 2

1

你不能像那样引用 Many2ManyField,你必须在类中使用一个方法stores,看起来像这样

def get_tags(): 
    return self.storeTags.all()

并在你的list_display(...'get_tags')

这样做是因为 M2M 字段会导致大量 SQL 查询,这会使整个事情变慢,因此选择必须来自开发人员而不是框架。

于 2013-04-15T18:04:19.223 回答
0

请检查:

ModelAdmin.list_display

“不支持 ManyToManyField 字段,因为这需要为表中的每一行执行单独的 SQL 语句。如果您仍然想这样做,请为您的模型提供自定义方法,并将该方法的名称添加到 list_display。(见下文有关 list_display 中自定义方法的更多信息。)”

您可以使用自定义方法来显示 ManyToManyField 的值或简单地storeTagslist_display

于 2013-04-15T15:39:51.117 回答