使用GenericForeignKey在模型表单上显示admin中的相关内联

时间:2022-03-12 20:04:11

I have simple models with generic relations from this example at the Django Project:

我在Django项目中有这个例子的简单模型和泛型关系:

class Image(models.Model):
    image = models.ImageField(upload_to="images")

class ImageLink(models.Model):
    image = models.ForeignKey(Image)
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey("content_type", "object_id")

class Product(models.Model):
    name = models.CharField(max_length=100)

It's very simple to show inline ImageLink objects on the admin form of Product. It is demonstrated in the Django docs.

在Product的管理表单上显示内联ImageLink对象非常简单。它在Django文档中得到了证明。

Can anyone suggest how have related ImageLinks inline on the admin form of an Image model?

任何人都可以建议如何在Image模型的管理表单上内联相关的ImageLinks?

IMPORTANT UPDATE: Updated example of model, becourse with previous, as Daniel sayd, it's not need to show objects inline.

重要更新:模型的更新示例,正如前面所述,正如丹尼尔所说,它不需要内联显示对象。

2 个解决方案

#1


It's neccessary use generic.GenericTabularInline for showing ImageLink objects inline on the Product form, as demonstrated in the Django docs.

必须使用generic.GenericTabularInline在Product表单上内联显示ImageLink对象,如Django文档中所示。

But if we need to show related ImageLink inline on the Image form, it can be done with simple child of admin.TabularInline class.

但是如果我们需要在Image表单上内联显示相关的ImageLink,可以使用admin.TabularInline类的简单子项来完成。

It's very simple solution. I think I'm stupid not to guess it right away.

这是非常简单的解决方案。我觉得我很蠢,不要马上猜它。

#2


You don't have any related Products to show inline. Generic foreign keys, like normal ones, are one-to-many, with the 'one' side of the relation being the one containing the foreign key field. So in your case you still only have one Product for each Image, so there is no inline set to show.

您没有任何内联显示的相关产品。与普通外键一样,通用外键是一对多的,关系的“一”侧是包含外键字段的外键。因此,在您的情况下,每个图像仍然只有一个产品,因此没有要显示的内联集。

#1


It's neccessary use generic.GenericTabularInline for showing ImageLink objects inline on the Product form, as demonstrated in the Django docs.

必须使用generic.GenericTabularInline在Product表单上内联显示ImageLink对象,如Django文档中所示。

But if we need to show related ImageLink inline on the Image form, it can be done with simple child of admin.TabularInline class.

但是如果我们需要在Image表单上内联显示相关的ImageLink,可以使用admin.TabularInline类的简单子项来完成。

It's very simple solution. I think I'm stupid not to guess it right away.

这是非常简单的解决方案。我觉得我很蠢,不要马上猜它。

#2


You don't have any related Products to show inline. Generic foreign keys, like normal ones, are one-to-many, with the 'one' side of the relation being the one containing the foreign key field. So in your case you still only have one Product for each Image, so there is no inline set to show.

您没有任何内联显示的相关产品。与普通外键一样,通用外键是一对多的,关系的“一”侧是包含外键字段的外键。因此,在您的情况下,每个图像仍然只有一个产品,因此没有要显示的内联集。