django、contenttype 和 m2m 通用关系
我有以下型号:
- 应用
- 联系表
- 游戏
- 着陆页
- 客户端
添加新客户端后,我想在客户端下添加新应用程序。为此,我在“客户端到应用程序”下添加了一个 m2m 字段,如下所示:
applications = models.ManyToManyField(Application, verbose_name=u'Applications')
由于应用程序可以是任何内容,因此我发现我需要使用内容类型框架。因此,我将以下内容放置在“应用程序模型”下:
applicationContentType = models.ForeignKey(ContentType)
applicationId = models.PositiveIntegerField()
application = generic.GenericForeignKey('applicationContentType', 'applicationId')
这样,我可以通过选择内容类型(本例中为内容表单)并键入现有联系表单的 ID 来添加新应用程序。我可以在管理页面上的客户 m2m 字段中看到它。
但是,当我执行以下操作时,我看不到刚刚添加到客户端的应用程序:
In [2]: t = Client.objects.get()
In [3]: t.applications.all()
Out[3]: []
并且必须记住新添加的联系表单的 ID 并不是很好。有一个优雅的解决方案吗?或者我应该改变对问题的看法并以不同的方式来做?
I have the following models:
- Application
- Contact Form
- Game
- Landing Page
- Client
After I add a new Client, I want to add new applications under client. For this, I added a m2m field under Clients to Applications like this:
applications = models.ManyToManyField(Application, verbose_name=u'Applications')
Since an application can be anything, I found out that I needed to use contenttype framework. So I placed the following under Application model:
applicationContentType = models.ForeignKey(ContentType)
applicationId = models.PositiveIntegerField()
application = generic.GenericForeignKey('applicationContentType', 'applicationId')
This way I can add new applications by selecting content type (content form in this case) and typing existing Contact Form's id. And I can see it in Client's m2m field on admin page.
However when I do the following, I can't see the application I just added to the Client:
In [2]: t = Client.objects.get()
In [3]: t.applications.all()
Out[3]: []
And having to remember the newly added Contact Form's id is not very nice. Is there an elegant solution of this? Or should I change my point of view to the problem and do it in a different way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
注意:我知道这是一个非常古老的问题,但认为有人可能会受益
如果每个应用程序模型(或 其
abstract
父级)将有一个 m2m 密钥客户。我不建议使用通用外键,除非它绝对不可避免(相信我,你稍后会感谢我)。例如,采用应用程序模型:
使用此方法,您将分别通过
lated_games
、lated_contactforms
和lated_landingpages
向客户端提供反向字段。Note: I know this is a very old question, but thought someone might benifit this
What you are describing would work perfectly if the each of the application models (or their
abstract
parent) would have a m2m key to the client. I would not recommend using generic foreign keys unless it's absolutely inevitable (trust me, you'll thank me later).For instance, take an application model:
Using this approach you will have the reverse fields available to the client via the
related_games
,related_contactforms
andrelated_landingpages
respectively.