我试图在django中定义2个模型,如下所示:
class Selector(models.Model):
# A Beautiful Soup selector
selector = models.CharField(max_length=ELEMENT_SELECTOR_MAX_LENGTH, null=True, blank=True)
def __str__(self):
return self.selector
class Provider(models.Model):
# Articles' parent container selector
articles_parent_container_selector = models.ForeignKey(Selector, related_name="articles_parent_container",
help_text=_("Beautiful Soup selector for all articles' "
"parent container"))
# Article's parent container selector
article_parent_container_selector = models.ForeignKey(Selector, related_name="article_parent_container_selector",
help_text=_("Beautiful Soup selector for each article"))
等。等等 我们的想法是为Provider模型的每个字段设置多个选择器。
我试图在管理应用程序中实现的目标是为提供者模型的每个字段提供charField内联。
所以我的admin.py就像
from django.contrib import admin
from .models import Provider, Selector
class SelectorInline(admin.StackedInline):
model = Selector
class ProviderAdmin(admin.ModelAdmin):
inlines = [
SelectorInline,
]
admin.site.register(Provider, ProviderAdmin)
我收到错误
<class 'news_providers.admin.SelectorInline'>: (admin.E202) 'news_providers.Selector' has no ForeignKey to 'news_providers.Provider'.
我也试过
class SelectorInline(admin.StackedInline):
model = Selector
fk_name = 'articles_parent_container'
如此处所述:Django inline forms with multiple foreign keys
但现在的错误是:
<class 'news_providers.admin.SelectorInline'>: (admin.E202) 'news_providers.Selector' has no field named 'articles_parent_container'.
还尝试将我的关系更改为ManyToMany(这似乎与我的用例更相关)并应用此处找到的hack:http://www.mc706.com/tip_trick_snippets/18/django-manytomany-inline-admin/,但没有运气:/
这应该是非常直接的,但我担心django开发人员没有注意到这个用例?
谢谢!
答案 0 :(得分:1)
显然,没有内置功能可以在另一个模型页面中显示内联的manyToMany模型。
你能做的最好的就是定义模型
models.py
class Selector(models.Model):
# A Beautiful Soup selector
selector = models.CharField(max_length=70, null=True, blank=True)
class Provider(models.Model):
# Articles' parent container selector
articles_parent_container_selector = models.ManyToManyField(Selector, blank=True,
help_text=_("Beautiful Soup selector for all articles' "
"parent container."),
related_name='articles_parent_container')
admin.py
class ArticlesParentContainerSelectorInline(admin.TabularInline):
model = Provider.articles_parent_container_selector.through
verbose_name = "Articles' parent container selector"
class ProviderAdmin(admin.ModelAdmin):
inlines = [
ArticlesParentContainerSelectorInline,
]
exclude = ('articles_parent_container_selector',)
admin.site.register(Provider, ProviderAdmin)
这有点令人失望,因为我期望得到文本输入而不是下拉菜单(甚至两者都有),所以我可以添加选择器而无需点击加号......
我倾向于为管理应用程序创建自己的小部件。
无论如何,感谢所有打扰阅读的人!