我是Django的初学者,我正在尝试使用Array来订购评论..
我在models.py
中有这个类class Comment(models.Model):
line_combination = models.ForeignKey(LineCombination, null=False, blank=False, default=1, on_delete=models.CASCADE)
name = models.CharField(max_length=100 , null=True , blank=True)
email = models.CharField(max_length=250,null=True , blank=True)
comment = models.TextField()
class Meta:
ordering = ['line_combination__line__name']
对于行组合我有这个类:
class LineCombination(models.Model):
line = models.ForeignKey(Line, null=False, blank=False, on_delete=models.CASCADE)
combinations = models.ManyToManyField(GenoType, blank=False)
class Meta:
# Ordering the names of line Alphabetically
ordering = ['line__name']
对于GenoType我有这个类:
class GenoType(models.Model):
name = models.CharField(max_length=250, null=False, blank=False)
我想在类评论中进行排序 line_combination.combinations.name 像这样:
ordering = ['line_combination__line__name' , 'line_combination__combinations__name']
但是 line_combination.combinations.name 是数组所以我不能把它作为值..
那我怎么办呢?
提前致谢..
答案 0 :(得分:0)
一个LineCombination
有很多GenoType
个,因此,如果我们不想,我们必须确定来自GenoType
的哪一行应用于LineCombination
排序收到重复的结果。
您可以手动确定此行:
class LineCombination(models.Model):
line = models.ForeignKey(Line, null=False, blank=False)
combinations = models.ManyToManyField(GenoType)
main_combination = models.ForeignKey(GenoType, null=True, blank=True)
然后ordering = ['line_combination__main_combination__name']
。
在这种情况下,您必须添加一些逻辑来填充main_combination
字段,例如在表单或signals中。
或者你可以select this row when run queries:
from django.db.models import Min
Comment.objects \
.annotate(main_name=Min('line_combination__combinations__name')) \
.order_by('main_name')