[英]Order the objects in the field ManyToMany
gt.tests - ManyToMany field with model Test. gt.tests-模型为Test的ManyToMany字段。 I need to sort the tests by this strange algorithm, but the question is different.
我需要通过这种奇怪的算法对测试进行排序,但问题有所不同。 After all the operations, I get a sorted list of tests and add them to the ManyToMany field.
完成所有操作后,我得到了一个排序的测试列表,并将它们添加到ManyToMany字段中。 But when I take the value tests from this field, they are displayed in order from the smallest id test to the largest.
但是,当我从该字段中进行值测试时,它们按照从最小id测试到最大id的顺序显示。 How do I add tests to this field in my order?
如何按我的顺序向该字段添加测试?
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()])
You should use a through model. 您应该使用直通模型。
Sample usage of a through model: 直通模型的样本用法:
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)
When inserting into the QuestionTest model you need to specify the sort_field, and when getting the tests related to the question you should use something like this. 当插入到QuestionTest模型中时,您需要指定sort_field,并且在获取与问题相关的测试时,应使用类似以下的内容。
Question.objects.get(id=1).tests.all().order_by("questiontest__sort_field")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.