<p>问题是你有不同的型号,这使得操作非常昂贵。
我建议您添加一个新模型,其中所有要查询的模型都注册为外键或id/类型对。这样,您就可以绕过设计缺陷</p>
<ol>
<li><p>仅拉动ID:
model.objects.all().values\u list('id',flat=True)。
random.sample的结果将是id,您可以直接使用id拉帖子</p></li>
<li><p>生成新表的1到count()之间的随机范围,然后通过处理具有相应索引的记录来提取实际的POST。这需要您添加一个索引字段,因为id可能不是连续的(删除和填充)</p></li>
</ol>
<p>获得id后,您可以使用model.objects.filter(id\uuuu in=post\u建议书)提取集合并进一步处理它</p>
<p>-编辑示例实现-</p>
<p>环绕其他模型的模型将如下所示:</p>
<pre><code>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')
</code></pre>