python - django - 一个内联多个模型

标签 python django django-models inline

我有内联:

class GenderInline(admin.StackedInline):
    model = models.GenderModel1
    extra = 0

我想在不同的管理表单中使用这个内联。

一旦我希望他的模型为 models.GenderModel1,一旦为 models.GenderModel2(根据 AdminForm,此内联是相关的)

我可以这样做吗?或者唯一的方法是复制内联? (我不喜欢...我需要复制 10 个内联...):

class GenderInline1(admin.StackedInline):
    model = models.GenderModel1
    extra = 0

class GenderInline2(admin.StackedInline):
    model = models.GenderModel2
    extra = 0

最佳答案

实际上,您可以使用 type 动态创建类,以避免定义多个类。定义一个创建内联函数,如下所示:

def get_inline_by_model(m):
    return type(
        'DynamicInline', 
        (admin.StackedInline, ), 
        {'model':m, 'extra':0} 
    )

And then in your Admin class you can just define your inline like:

inlines = ( get_inline_by_model (models.GenderModel1 ) ,  ) 

关于python - django - 一个内联多个模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22991098/

相关文章:

python - 如何使用 python 验证 mp4 文件或音频文件?

模型 Mixin 中的 Django GenericRelation

python - 是否可以减少样板函数上的参数数量?

django admin 不会将对象添加到 Manytomany 字段中

python - Django不会在try except语句中重定向到404

python - 如果某些列表组件相同,如何防止列表处理函数进行重复操作?

python - 如何从特殊点切割字符串

python - 为 db tableD Django 创建别名

python - Airflow 安装错误 :"python setup.py egg_info"失败,错误代码为 1”

python - 如何将 torch.device ('cuda' if torch.cuda.is_available() else 'cpu' ) 写成完整的 if else 语句?