不幸的是,您不能在数据库或查询集级别执行此操作,因为这两个内容不存在于同一个数据库表中。您可以在 python 端执行此操作(尽管它更慢且计算量更大)。
假设 Cars 和 Horses 都有“日期”属性,您可以这样做:
cars = Cars.objects.all().filter(color='red')
horses = Horses.objects.all()
all_things = list(cars) + list(horses)
sorted_things = sorted(all_things, key=lambda x: x.date)
另一种选择(在数据库级别效率低下)是让它们都继承自同一个非抽象模型。
class Item(models.Model):
date = models.DateTimeFiedl()
item_type = models.CharField(max_length=255)
def get_instance(self):
if self.item_type = 'car':
return Car.objects.get(id=self.id)
elif self.item_type == 'horse':
return Horse.objects.get(id=self.id)
class Car(Item):
color = models.CharField(max_length=12)
def save(self, *args, **kwargs):
self.item_type = 'car'
super(Car, self).save(*args, **kwargs)
class Horse(Item):
breed = models.CharField(max_length=25)
def save(self, *args, **kwargs):
self.item_type = 'horse'
super(Horse, self).save(*args, **kwargs)
你可以这样做
items = Item.objects.all().order_by('date')
for item in items:
print(type(item)) # Always "Item"
actual_item = item.get_instance()
if type(actual_item) == Car:
print("I am a car")
else:
print("I am a horse")
在遍历它们时,根据需要抓取每个特定项目(类似于 Wagtail 处理页面的方式,您可以创建一个方便的方法来根据其父类抓取对象)