简体   繁体   English

Django,ContentType和M2M通用关系

[英]django, contenttype and m2m generic relations

I have the following models: 我有以下型号:

  1. Application 应用
    1. Contact Form 联系表
    2. Game 游戏
    3. Landing Page 登陆页面
  2. 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: 为此,我在“客户端”下为应用程序添加了一个m2m字段,如下所示:

applications = models.ManyToManyField(Application, verbose_name=u'Applications')

Since an application can be anything, I found out that I needed to use contenttype framework. 由于应用程序可以是任何东西,因此我发现我需要使用contenttype框架。 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. 这样,我可以通过选择内容类型(在这种情况下为内容表单)并键入现有的联系表单ID来添加新的应用程序。 And I can see it in Client's m2m field on admin page. 我可以在管理页面的“客户的m2m”字段中看到它。

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. 而且必须记住新添加的联系表单的ID并不是很好。 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? 还是应该改变我对问题的看法并以其他方式解决?

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. 如果每个应用程序模型(或其abstract父级 )都具有一个指向客户端的m2m密钥,那么您所描述的内容将非常有效。 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: 例如,采用一个应用程序模型:

class Application(models.Model):
    class Meta:
        abstract = True

    field1 = ...
    field2 = ...

    client = models.ManyToManyField('clients.Client',
                                    related_name="related_%(class)s")

Using this approach you will have the reverse fields available to the client via the related_games , related_contactforms and related_landingpages respectively. 使用这种方法,您将分别通过related_gamesrelated_contactformsrelated_landingpages向客户端提供反向字段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM