简体   繁体   English

Django中的一对多关系

[英]One-to-many relationships in Django

I'm trying to create a One-to-many relationship in Django. 我正在尝试在Django中创建一对多关系。 In my example, I have a news post, which may have several images associated with it. 在我的示例中,我有一个新闻帖子,其中可能有多个与之相关的图像。 However, different news posts will never share images. 但是,不同的新闻帖子将永远不会共享图像。

As far as I can see, there are two ways to do this: Through a ManyToManyField , which creates a multi-select tool in the admin panel, which shows all the images ever uploaded, or through a ForeignKeyField in the PostImage class, which results in there not being any option to add new images when creating a new news post on the admin panel. 据我所知,有两种方法可以执行此操作:通过ManyToManyField ,它在管理面板中创建一个多选工具,以显示曾经上传的所有图像,或者通过PostImage类中的ForeignKeyField来生成结果在管理面板上创建新新闻时,没有任何选项可以添加新图像。

Since the users of the admin panel will not be at all technically-inclined, I would like two things, if possible: 由于管理面板的用户根本不会在技术上有所偏向,因此,我希望有两件事,如果可能的话:

  • Add several images on the "Create new news post" page, without having any images from other news posts as a choice 在“创建新新闻”页面上添加几张图片,而不必选择其他新闻中的任何图片
  • Less importantly, replace the multi-select box with checkboxes, or anything less confusing than a multi-select box. 不太重要的是,将复选框替换为复选框,或者将其替换为比复选框更容易混淆的内容。

How can I achieve this? 我该如何实现?

The second part is the easier one: You want the horizontal javascript filter 第二部分比较简单:您需要水平javascript过滤器

If you go with a ManyToManyField, you could filter those choices by using a Custom Manager . 如果使用ManyToManyField,则可以使用Custom Manager过滤这些选择。

If you use a ForeignKey, you would want to use one of the Admin Inlines . 如果您使用ForeignKey,则需要使用Admin Inlines之一 If you really never re-use images, use the inlines. 如果您确实从未重复使用图像,请使用内联。

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

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