2 回答
TA贡献1829条经验 获得超6个赞
问题是你有不同的模型,这使得操作非常昂贵。我建议您添加一个新模型,其中您要查询的所有模型都注册为外键或 id/type 对。有了它,您可以绕过设计缺陷,并且
仅提取 id:model.objects.all().values_list('id',flat=True)。random.sample 的结果将是 ids,您可以直接使用 id 拉出帖子
在新表的 1 和 count() 之间生成一个随机范围,然后通过处理具有相应索引的记录来提取实际帖子。这将需要您添加一个索引字段,因为 id 可能不是连续的(删除和填充)
获得 ID 后,您可以使用 model.objects.filter(id__in=post_proposals) 拉取集合并进一步处理
--- 编辑示例实现 ---
环绕其他模型的模型看起来像这样:
class Model1(models.Model):
@staticmethod
def get_ref_type(): return 0
def create(self):
super(Model1,self).create()
Posts.register(self,Model1.get_ref_type())
def delete(self):
Posts.un_register(self,Model1.get_ref_type())
super(Model1,self).delete()
class Posts(models.Model):
class Meta:
....
#sequential index, this is what you will filter against
index = models.IntegerField(default=0)
#type of the model you want to query
ref_type = models.IntegerField(default =-1)
#id of the record in the table defined in the ref_type field
ref_id = models.IntegerField(default =-1)
@staticmethod
def register(f_objRecord,f_intType):
l_objWrp = Posts()
#a separate table that will be used to hold the free indexes
#it will ensure that even when you delete records, there
#won't be any holes in the set
l_objWrp.index = PostIndex.get_index()
l_objWrp.ref_id = f_objRecord.id
l_objWrp.ref_type = f_intType
l_objWrp.save()
@staticmethod
def un_register(f_objRecord,f_intType):
l_objWrp = Posts.objects.get(ref_type=f_intType,ref_id=f_objRecord.id)
PostIndex.free_index(l_objWrp.index)
l_objWrp.delete()
def get_data(self):
l_intRefType = self.ref_type
l_intId = self.ref_id
l_objRecord = None
if l_intRefType == Model1.get_ref_type():
l_objRecord = Model1.objects.get(id=l_intId)
elif l_intRefType == Model2.get_ref_type():
.....
if l_objRecord:
#pull the data you want
else: raise('unknown model type')
添加回答
举报