from django.db import models
from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
from django.contrib.contenttypes.models import ContentType
class Index(models.Model):
"""通用模型类"""
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
pub_date = models.DateField()
class Meta:
ording = [-"pub_date"]
class News(models.Model):
"""动态"""
content = models.CharField(max_length=255)
pub_date = models.DateTimeField(auto_now_add=True)
index = GenericRelation(Index)
def save(self, force_insert=False, force_update=False, using=None,
update_fields=None):
self.index.get_or_create(pub_date=self.pub_date)
class Article(models.Model):
"""文章"""
title = models.CharField(max_length=255)
pub_date = models.DateTimeField(auto_now_add=True)
index = GenericRelation(Index)
def save(self, force_insert=False, force_update=False, using=None,
update_fields=None):
self.index.get_or_create(pub_date=self.pub_date)
class Question(models.Model):
"""问题"""
q_title = models.CharField(max_length=255)
content = models.CharField(max_length=255)
pub_date = models.DateTimeField(auto_now_add=True)
index = GenericRelation(Index)
def save(self, force_insert=False, force_update=False, using=None,
update_fields=None):
self.index.get_or_create(pub_date=self.pub_date)
这样就可以通过Index来查询其他三个模型类的数据,然后根据 ording 来倒叙排列