在ManyToMany字段中订购对象

时间:2018-11-07 19:08:44

标签: python django many-to-many

gt.tests-模型为Test的ManyToMany字段。我需要通过这种奇怪的算法对测试进行排序,但问题有所不同。完成所有操作后,我得到了一个排序的测试列表,并将它们添加到ManyToMany字段中。但是,当我从该字段中进行值测试时,它们按照从最小id测试到最大id的顺序显示。如何在我的订单中向该字段添加测试?

    tests = Test.objects.all()
    gt = GroupTest.objects.create(title=name, user=user)

    #code

    import random
    tests_array = []
    tests_go = []

    for reading in ReadingForTest.objects.all():
        if tests.filter(reading=reading).count() != 0:
            tests_array.append(tests.filter(reading=reading))

    tests_list = tests.filter(reading__isnull=True)

    while len(tests_list) > 0:
        number = random.randint(0, 5)
        tests_array.append(tests_list[:number])
        tests_list = tests_list[number:]

    seq = [x for x in range(len(tests_array))]

    random.shuffle(seq)

    for i in seq:
        tests_go.extend(tests_array[i])

    tests_go = tests_go[:number_of_questions]

    print_arr = []
    for test in tests_go:
        print_arr.append(test.id)
        gt.tests.add(test)

    print(print_arr)
    print([x.id for x in gt.tests.all()])

屏幕截图输出here

1 个答案:

答案 0 :(得分:1)

您应该使用直通模型。

直通模型的示例用法:

class Question(models.Model):
    value = models.TextField()

class Test(models.Model)
    value = models.TextField()
    questions = models.ManyToManyField(Question, related_name="tests", through="QuestionTest")

class QuestionTest(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    test = models.ForeignKey(Test, on_delete=models.CASCADE)
    sort_field = models.IntegerField(default=0)

在插入QuestionTest模型中时,您需要指定sort_field,在获取与问题相关的测试时,应使用类似这样的内容。

Question.objects.get(id=1).tests.all().order_by("questiontest__sort_field")