2 回答

TA貢獻1829條經(jīng)驗 獲得超6個贊
問題是你有不同的模型,這使得操作非常昂貴。我建議您添加一個新模型,其中您要查詢的所有模型都注冊為外鍵或 id/type 對。有了它,您可以繞過設(shè)計缺陷,并且
僅提取 id:model.objects.all().values_list('id',flat=True)。random.sample 的結(jié)果將是 ids,您可以直接使用 id 拉出帖子
在新表的 1 和 count() 之間生成一個隨機范圍,然后通過處理具有相應(yīng)索引的記錄來提取實際帖子。這將需要您添加一個索引字段,因為 id 可能不是連續(xù)的(刪除和填充)
獲得 ID 后,您可以使用 model.objects.filter(id__in=post_proposals) 拉取集合并進一步處理
--- 編輯示例實現(xiàn) ---
環(huán)繞其他模型的模型看起來像這樣:
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')
添加回答
舉報