问题描述
我有2个模型:Page
和Section
。一个Page
对象可以具有一对多Section
对象。
在models.py
中:
class Page(models.Model):
name = models.CharField(max_length=100,help_text='Name of the page.')
class Meta:
ordering = ['id']
class Section(models.Model):
page = models.ForeignKey(Page,on_delete=models.CASCADE)
name = models.CharField(max_length=100,help_text='Name of the section.')
index = models.IntegerField(blank=True,help_text='Index number to sort section.')
class Meta:
ordering = ['id']
index
对象中的 Section
指示其在其余Section
个对象中具有与外键相同的Page
对象的其余serializers.py
对象中的顺序(位置)。
在class SectionSerializer(serializers.ModelSerializer):
page = serializers.PrimaryKeyRelatedField(queryset=Page.objects.all(),many=False,required=True)
class Meta:
model = Section
fields = ['id','page','name','index']
class PageSerializer(serializers.ModelSerializer):
sections = SectionSerializer(source='section_set',many=True,required=False) # problem is here.
# can I do something like source="section_set.order_by('index')"
class Meta:
model = Page
fields = ['id','sections']
中:
sections
使用PageSerializer
中的Section
属性,我可以获得具有与外键相同的Page
对象的所有index
对象。但未按其Page.objects.all
字段排序。
当我使用PageSerializer
查询[
{
"id":1,"name":"Home","sections":[
{
"id":10,"page":1,"name":"second_section_for_page_1","index":2
},{
"id":11,"name":"first_section_for_page_1","index":1
},{
"id":12,"name":"third_section_for_page_1","index":3
}
]
},{
"id":2,"name":"Profile","sections":[
{
"id":13,"page":2,"name":"second_section_for_page_2",{
"id":14,"name":"first_section_for_page_2","index":1
}
]
}
]
时,在可浏览的API中得到了以下结果:
index
我希望按[
{
"id":1,"sections":[
{
"id":11,{
"id":10,"sections":[
{
"id":14,{
"id":13,"index":2
}
]
}
]
对结果进行排序。像这样:
sections = SectionSerializer(source="section_set.order_by('index')")
我可以在PageSerializer
类中做类似nodetool getendpoints
的事情吗?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)