使用自定义等价的 Django 不同查询
django distinct query using custom equivalence
假设我的模型是这样的:
class Alert(models.Model):
datetime_alert = models.DateTimeField()
alert_type = models.ForeignKey(Alert_Type, on_delete=models.CASCADE)
dismissed = models.BooleanField(default=False)
datetime_dismissed = models.DateTimeField(null=True)
auid = models.CharField(max_length=64, unique=True)
entities = models.ManyToManyField(to='Entity', through='Entity_To_Alert_Map')
objects = Alert_Manager()
def __eq__(self, other):
return isinstance(other,
self.__class__) and self.alert_type == other.alert_type and \
self.entities.all() == other.entities().all() and self.dismissed == other.dismissed
def __ne__(self, other):
return not self.__eq(other)
我想要完成的是这样说:如果解除状态、警报类型和关联实体相同,则两个警报对象是等价的。使用这个想法,是否可以编写一个查询来根据该标准请求所有不同的警报?选择所有这些然后将它们过滤掉似乎并不吸引人。
你说了一种方法,我觉得还不错。我不知道 Django 中有什么可以做到这一点。
但是,我要你想想为什么会出现这个问题?如果消息、状态和类型相同时两个警报相等,那么也许这应该是它自己的 class。我会考虑创建另一个 class DistinctAlert
(或更好的名称),并从 Alert
获得此 class 的外键。或者更好的是,有一个 class 即 Alert
,还有一个叫做 AlertEvent
(你的 Alert
class)。
这会解决您的问题吗?
编辑:
实际上,有一种方法可以做到这一点。您可以组合 values()
和 distinct()
。这样,您的查询将是
Alert.objects.all().values("alert_type", "dismissed", "entities").distinct()
这将 return 字典。
中查看更多信息
假设我的模型是这样的:
class Alert(models.Model):
datetime_alert = models.DateTimeField()
alert_type = models.ForeignKey(Alert_Type, on_delete=models.CASCADE)
dismissed = models.BooleanField(default=False)
datetime_dismissed = models.DateTimeField(null=True)
auid = models.CharField(max_length=64, unique=True)
entities = models.ManyToManyField(to='Entity', through='Entity_To_Alert_Map')
objects = Alert_Manager()
def __eq__(self, other):
return isinstance(other,
self.__class__) and self.alert_type == other.alert_type and \
self.entities.all() == other.entities().all() and self.dismissed == other.dismissed
def __ne__(self, other):
return not self.__eq(other)
我想要完成的是这样说:如果解除状态、警报类型和关联实体相同,则两个警报对象是等价的。使用这个想法,是否可以编写一个查询来根据该标准请求所有不同的警报?选择所有这些然后将它们过滤掉似乎并不吸引人。
你说了一种方法,我觉得还不错。我不知道 Django 中有什么可以做到这一点。
但是,我要你想想为什么会出现这个问题?如果消息、状态和类型相同时两个警报相等,那么也许这应该是它自己的 class。我会考虑创建另一个 class DistinctAlert
(或更好的名称),并从 Alert
获得此 class 的外键。或者更好的是,有一个 class 即 Alert
,还有一个叫做 AlertEvent
(你的 Alert
class)。
这会解决您的问题吗?
编辑:
实际上,有一种方法可以做到这一点。您可以组合 values()
和 distinct()
。这样,您的查询将是
Alert.objects.all().values("alert_type", "dismissed", "entities").distinct()
这将 return 字典。
中查看更多信息