Django模型:基于反向关系中一对多关系的排序来定义str_method



我有一个模型Stem,它与模型Question有一对多的关系(一个Stem包含许多问题(。

我想为CCD_ 4定义CCD_;词干标题+该词干中问题的索引";。例如,如果茎被称为"茎";Foo";,我希望stem中所有问题的str方法返回如下:

  • 第一个问题:"Foo-1">
  • 第二个问题:;Foo-2">
  • 第n个问题:;Foo-n">

实现这一目标的最佳方法是什么?

型号.py

class Stem(models.Model):
title = models.CharField(max_length=255)
stem = models.CharField(max_length=255)
class Question(Updated):  
stem = models.ForeignKey(
Stem, related_name='question', on_delete=models.DO_NOTHING, null=True, blank=True)
question = models.CharField(max_length=255)
def __str__(self):
return **What do I put here**

最简单的方法可能是查询其他问题的id,并在该列表中查找当前问题的id。还有一些其他情况需要处理,其中stem为null或Question未保存:

def __str__(self):
# handle the case where stem is null
if self.stem is None:
return "Question for unknown stem"  # or whatever you prefer
# handle the case where the Question is unsaved
if self.id is None:
return f"{self.stem.title}-unsaved"  # or whatever you prefer
# make sure you order the self.stem.question queryset
# so you have a consistently ordered result. Not sure if id is the correct
# ordering here but there are not many other options
question_ids = list(self.stem.question.order_by("id").values_list("id", flat=True))
my_index = question_ids.index(self.id) + 1  # adding 1 based on your requirements
return f"{self.stem.title}-{my_index}"

您也可以考虑使用row_number的窗口函数,但我认为以上可能是更好的方法。

实际上,一个好的方法可以是:

# Assuming that the value of index is the nth value which is referred in the queryset
# specific to the question with the stem value
class Question(Updated):  
stem = models.ForeignKey(
Stem, related_name='question', on_delete=models.DO_NOTHING, null=True, blank=True)
question = models.CharField(max_length=255)
def get_index(self):
stem_obj = self.stem
questions = stem_obj.question.all()
counter=0
for question in questions:
counter+=1
if question==self:
return counter
def __str__(self):
return f"{self.stem.title}-{self.get_index()}"

最新更新