你不能在数据库或查询集级别做到这一点,因为不幸的是这两件事情并不在同一个数据库表中。你可以在python方面做到这一点(虽然速度更慢,计算量更大)。
假设这两款车和马有一个“日期”的属性,你可以这样做:
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")
在遍历他们需要抓住每一个具体的项目(类似于鹡鸰如何处理页面,您为抓取对象的便捷方法,基于其父类)
你不能做到这一点。定义的查询集是来自单个模型的一组对象。 –