【问题标题】:django How to randomly merge two different querysets (but with some fields in common)django 如何随机合并两个不同的查询集(但有一些共同的字段)
【发布时间】:2021-06-22 08:04:11
【问题描述】:

我正在使用 Django 3.2

我有两个看起来有点像这样的模型:

class A(models.Model):
    title = models.CharField(max_length=255)
    caption = models.CharField(max_length=64)
    image = models.ImageField()

    # ... other fields unique to this model only


class B(models.Model):
    title = models.CharField(max_length=255)
    caption = models.CharField(max_length=64)
    image = models.ImageField()

    # ... other fields unique to this model only

我希望能够写出这样的函数:

def get_modelA_records_with_randomly_inserted_modelB(criteria_for_A, criteria_for_B, page_num):
    qs_A = get_records_for_modelA(criteria_for_A, page_num)
    qs_B = get_records_for_modelB(criteria_for_B, page_num)

    # Randomly insert records of B into list of records of A
    new_qs = qs_A | qs_B # how?

一个简单的方法是费力地遍历qs_A,根据随机布尔标志插入qs_B元素-但我想知道是否有更pythonic或“djangoistic”的方法来做到这一点?

【问题讨论】:

    标签: python django django-queryset


    【解决方案1】:

    我现在无法在 PC 上进行测试,但我认为您可能可以这样做:

    new_qs = qs_a | qs_b
    new_qs = new_qs.order_by('?')
    

    查询集是懒惰地评估的,所以只要你在随机订购之前不尝试使用它(迭代它),我认为这应该可以工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-24
      • 2021-01-02
      • 2020-08-31
      • 1970-01-01
      • 1970-01-01
      • 2016-01-02
      • 2018-10-03
      • 2019-08-11
      相关资源
      最近更新 更多