如何在django管理员中添加双向的多个域? [英] How to add bi-directional manytomanyfields in django admin?

查看:72
本文介绍了如何在django管理员中添加双向的多个域?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  class LocationGroup(models.Model):
name = models.CharField(max_length = 200)

类报告(models.Model):
name = models.CharField(max_length = 200)
locationgroups = models.ManyToManyField(LocationGroup )

admin.py(standard):

  admin.site.register(LocationGroup)
admin.site.register(Report)

当我输入报告的管理页面时,它显示一个很好的多选字段。如何在LocationGroup中添加相同的多项选择字段?我可以通过调用LocationGroup.report_set.all()

解决方案

访问所有报告我找到的解决方法是按照<一个href =http://docs.djangoproject.com/en/dev/ref/contrib/admin/#working-with-many-to-many-intermediary-models =noreferrer> ManyToManyFields与中介模型。即使您没有使用'通过'模式功能,只要假装就像您一样,并创建具有必要ForeignKey的存根模型。

 #models:确保命名约定符合ManyToManyField将创建的
class Report_LocationGroups(models.Model):
locationgroup = models.ForeignKey(LocationGroup)
report = models.ForeignKey (报告)

#admin
class ReportInline(admin.TabularInline):
model = models.Report_LocationGroups

class LocationGroupAdmin(admin.ModelAdmin):
inlines = ReportInline,


In my models.py i have something like:

class LocationGroup(models.Model):
    name = models.CharField(max_length=200)

class Report(models.Model):
    name = models.CharField(max_length=200)
    locationgroups = models.ManyToManyField(LocationGroup)

admin.py (standard):

admin.site.register(LocationGroup)
admin.site.register(Report)

When I enter the admin page for Report, it shows a nice multiple choice field. How can I add the same multiple choice field in LocationGroup? I can access all Reports by calling LocationGroup.report_set.all()

解决方案

The workaround I found was to follow the instructions for ManyToManyFields with intermediary models. Even though you're not using the 'through' model feature, just pretend as if you were and create a stub model with the necessary ForeignKey.

# models:  make sure the naming convention matches what ManyToManyField would create
class Report_LocationGroups(models.Model):
    locationgroup = models.ForeignKey(LocationGroup)
    report = models.ForeignKey(Report)

# admin
class ReportInline(admin.TabularInline):
    model = models.Report_LocationGroups

class LocationGroupAdmin(admin.ModelAdmin):
    inlines = ReportInline,

这篇关于如何在django管理员中添加双向的多个域?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆