如何从id列表中获得一个Queryset而不使用循环?



我想使用id列表从数据库获取数据。我有一个模型。

class Point(models.Model):
p1 = models.IntegerField()
p2 = models.IntegerField()

这个模型在我的数据库中有一堆数据。我有一个id列表,其数据在我的数据库中可用。[1,2,3,3,4,1]

我想从列表的id中获取数据。我知道我可以在这里应用一个循环通过遍历列表来获取数据。我在寻找一个更好的解决方案。

我已经看到了Point.objects.filter(id__in=[1,2,3,3,4,1])的一些类似的解决方案,但它不返回重复值的对象,如1和3在我的列表的情况下。如果我的列表有重复值,我希望查询集有重复值。提前谢谢。

根据你的问题,理解这一点…

首先,您需要一个唯一标识符来获取具有相似值的对象。如。一组学生中有两个名字相同的学生。我们认为它是"鲍勃"。现在,为了识别学生"鲍勃"我必须找到,我需要他的卷号。我们都知道,投no。同样,您的ID列表必须包含他的主键,以确定您要调用的对象。

我希望这个答案能消除你的疑虑!

如果我正确地阅读了您的评论,那么您已经将ForeignKey放置在错误的类中,因为您现在拥有它的方式:

class Point(models.Model): 
p1 = models.IntegerField() 
p2 = models.IntegerField() 

class Graph(models.Model): 
user=models.ForeignKey(User, on_delete=models.CASCADE) 
date_created = models.DateTimeField(auto_now_add=True) 
point = models.ForeignKey(Point, on_delete=models.CASCADE)

每个点都有很多图。它应该是另一种方式,以便你有许多点到一个图:

class Point(models.Model): 
p1 = models.IntegerField() 
p2 = models.IntegerField()
graph = models.ForeignKey(Graph, on_delete=models.CASCADE)

class Graph(models.Model): 
user=models.ForeignKey(User, on_delete=models.CASCADE) 
date_created = models.DateTimeField(auto_now_add=True) 

然后,在你的视图中,你可以得到所有的Point在你的图形中,像这样:

graph = Graph.objects.get(user=..., date_created=...)
# Here is the filter that will give you all Points on the graph:
points = Point.objects.filter(graph=graph)
# If you need the points as an array
points_list = []
for point in points:
# Your logic here, or if you just need the array you could
# append to the points_list:
points_list.append(point)

请注意
我明白这仍然可能使用循环,并且points = Points.objects.filter(graph=graph)中的过滤器仍然不会重复相同的点。同样,即使Point可能是相同的位置,并且/或者可能与其他数据相关联,所有这些都是相同的,它仍然是一个具有自己的主键pk的唯一点。.

如果您仍然需要一个具有重复IDPoint的数组(在Python中,数组称为列表)S,然后你要做一个循环,但问题仍然存在。你真的需要Points的ID的吗?您是否使用ID在你的计算中?

最新更新