我有3个型号:
: execute('r! '.myscript.path.variablename)
我想过滤stations.objects(并获取其字段),使其仅包含给定route_id的站点。到目前为止,我只能写这一行,我猜这是错误的class stations(models.Model):
station_id = models.AutoField( primary_key=True )
station = models.CharField( max_length=20 )
station_code = models.CharField( max_length=10 )
class route(models.Model):
route_id = models.AutoField( primary_key=True )
class SequenceTable(models.Model):
id = models.AutoField( primary_key=True )
route_id = models.ForeignKey( route, on_delete=models.CASCADE)
station_id = models.ForeignKey(stations, on_delete=models.CASCADE)
sequence_no = models.IntegerField( null=True )
请帮我找到正确的解决方案
答案 0 :(得分:0)
你可以这样做。
station_ids = SequenceTable.objects.filter(route_id=rid).values_list('station_id', flat=True)
station_qs = stations.objects.filter(station_id__in=station_ids)
由于django的查询集的实现方式,这将只生成一个数据库查询。
回答评论。是的,你可以在这里(可能行不通)会给你一般的想法
def station_gen(rid):
triple = []
station_ids = SequenceTable.objects.filter(route_id=rid).values_list('station_id', flat=True)
for s in stations.objects.filter(station_id__in=station_ids):
if len(triple) == 3:
triple.pop(0)
triple.append(s)
yield triple
else:
triple.append(s)
# and inside your view
...
if request.method == 'POST':
rid = request.POST.get('rid',None)
for three_students in student_gen(rid):
...
print(three_students)