首页 > 解决方案 > get_object_or_404 继承的类

问题描述

我有一个抽象类Type,它有 3 个继承的类Type1 Type2 Type3,这 3 个类属性中的 70% 是相同的。

我想要这样;

Tip=get_object_or_404(Type,tournament__slug=tournamentslug,slug=slug,game__slug=gameslug,) 

但是类型是抽象类我无法获取对象或过滤器

views.py(现在)

def game_detail(request,tournamentslug,slug,gameslug):
        tip1=get_object_or_404(Type1, tournament__slug=tournamentslug,slug=slug,game__slug=gameslug,)
        tip2=get_object_or_404(Type2,tournament__slug=tournamentslug,slug=slug,game__slug=gameslug,)
        tip3=get_object_or_404(Type3,tournament__slug=tournamentslug,slug=slug,game__slug=gameslug,)

标签: djangodjango-modelsdjango-views

解决方案


您不能混合使用这 3 个模型,因为它们是不同的模型和数据库中的不同表。您需要创建自己的get_object_or_404接受查询集的内容,并在其中输入混合查询集,或者分别测试所有 3 个模型并在没有任何对象时自行引发 404。

或者,如果此类中 70% 的数据是相同的,也许您可​​以使用一个大模型将它们全部保留?只需将 Type1 Type2 Type3 合并为一个通用 Type 模型。IMO 这比创建 3 个名称中带有数字的类似模型更合理


推荐阅读