[英]Order the objects in the field ManyToMany
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()])
屏幕截圖輸出在這里
您應該使用直通模型。
直通模型的樣本用法:
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")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.