根据条件对行进行分组

javaCity

我有以下型号:

class Datacomponent(models.Model):
        id = models.IntegerField(db_column='ID', primary_key=True)  # Field name made lowercase.
        composition = models.ForeignKey(Composition, models.DO_NOTHING, db_column='Composition_ID', null=True, blank=True)  # Field name made lowercase.
        components = models.ForeignKey(Components, models.DO_NOTHING, db_column='Components_ID')  # Field name made lowercase.
        componentvalue = models.FloatField(db_column='ComponentValue')  # Field name made lowercase.



class Components(models.Model):
    id = models.IntegerField(db_column='ID', primary_key=True)  # Field name made lowercase.
    name = models.CharField(db_column='Name', max_length=45, blank=True, null=True)  # Field name made lowercase.

Datacomponent有相同的组合物(其为外键的多个行Composition的表)。

我的最终目标是Composition确定每个组件值是否在某些值范围内。在下面显示的方法中,我根本没有任何composition_id。

CompositionID   ComponentID  ComponentValue
   1               1            0.5
   1               2            0.3
   2               1            0.6
   2               2            0.4
   3               1            0.0
   3               2            0.1

因此,上表的查询将是:'获取所有具有componentid = 1和componentvalue__range =(minn [a],maxx [b])的合成ID。如果我们希望分量ID 1的补偿值为gte 0.5,而分量ID 2的补偿值为gte 0.3,则结果应为2,因为2的分量1为0.6,而Component2的值为0.4。

这是我的方法不起作用:

    queries = [Q(componentvalue__range = (minn[v], maxx[v]),
                 components__name    = "'"+v+"'",
                ) for v in minn]

    query = queries.pop()
    for item in queries:
        query |= item

    composition_ids = Datacomponent.objects.filter(query).values_list('composition_id', flat=True)

    print (composition_ids.count())
小实例

如果我对您的理解正确,那么类似的事情可能会有所帮助

发表评论后进行编辑。(希望这次我能更好地理解您)。您实际上是在Composition将comp1和comp2都在指定范围内的对象作为对象(?),然后可以实际从Composition模型中进行选择

首先添加related_name到您的compositionDatacomponent模型,类似“datacomp”,反向查询。

from django.db.models import Q

class Datacomponent(models.Model):
    composition = models.ForeignKey(Composition, related_name='datacomp', ..) 
    ...

comp_1_query = Q(datacomp__components_id=YOUR_COMP1_ID, datacomp__componentvalue_range=(YOUR_RANGE1_MIN, YOUR_RANGE1_MAX)
comp_2_query = Q(datacomp__components_id=YOUR_COMP2_ID, datacomp__componentvalue_range=(YOUR_RANGE2_MIN, YOUR_RANGE2_MAX)


Composition.objects\
           .select_related('datacomp')\ # you can for optimization  
           .filter(comp_1_query, comp_2_query)\ # Simply 'and' since you want both to match
           .values_list('id', 'datacomp__components_id', 'datacomp__componentvalue', flat=True)

这将使您在指定范围内具有component1和component2的成分。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章