按\u related()查询分组

2024-05-19 17:07:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我看过这个How to query as GROUP BY in django?但我好像没法让它工作

我有一个查询集,它带来了4个相关的表。我想返回“top table”中的值并将它们分组在一起

要分组的列有:area\u easting(E)、area\u northing(N)、context\u number(C)、sample\u number(S)

电流数据输出示例

E |N  |C  |S     |material
99|526|101|1 ... |seed
99|526|101|1 ... |grain
99|526|101|1 ... |pip
99|526|101|2 ... |seed
99|526|101|2 ... |grain
99|526|101|2 ... |pip

我只想返回E | N | C | S一次,但仍然能够列出与之相关的每种材料。不必创建另一个def就可以这样做吗

#views.py
def botany(request):
  botany = FractionMaterialsPresent.objects.select_related()
  template = 'botany/test.html'
  return render(request, template, {'botany': botany})

#models.py
class Botany(models.Model):
  botany_id = models.AutoField(primary_key=True)
  sample_id = models.IntegerField(blank=True, null=True)
  area_easting = models.IntegerField(blank=True, null=True)
  area_northing = models.IntegerField(blank=True, null=True)
  context_number = models.IntegerField(blank=True, null=True)
  sample_number = models.IntegerField(blank=True, null=True)
  entry_date = models.DateTimeField(auto_now_add=True)
  analysis_date = models.DateTimeField(auto_now=True)
  analyst = models.CharField(max_length=200, default='')
  notes = models.CharField(max_length=600, default='')

class Fraction(models.Model):
  fraction_id = models.AutoField(primary_key=True)
  botany_id = models.ForeignKey(Botany, db_column='botany_id', on_delete = models.PROTECT)
  proportion_analysed = models.DecimalField(max_digits=5, decimal_places=3)
  soil_volume = models.DecimalField(max_digits=15, decimal_places=4)
  sample_volume = models.DecimalField(max_digits=15, decimal_places=4)
  sample_weight = models.DecimalField(max_digits=15, decimal_places=4)

class FractionMaterialsPresent(models.Model):
  material_id = models.AutoField(primary_key=True)
  fraction_id = models.ForeignKey(Fraction, db_column='fraction_id', on_delete = models.PROTECT)
  material = models.CharField(max_length=200, default='')

Tags: sampleidtruenumbermodelsareanullmax