Django查询许多对象

时间:2018-07-24 19:08:59

标签: python django model

在Django模型中是否有一种查询方法,例如加入SQL?

result = []
for f in self.Functions.all():
    result = result + list(f.Properties.all())
return result

其中selfDevice对象

模型

class Property(models.Model):
    Id = ShortUUIDField(unique=True, primary_key=True, blank=False, editable=False)
    Name = models.CharField(max_length=50)
    Parameters = jsonfield.JSONField(default="{}")
    Value = models.CharField(max_length=50)
    Type = models.IntegerField(choices=[(choice.value, choice.name.replace("_", " ")) for choice in TypeEnum])
    Class = models.IntegerField(choices=[(choice.value, choice.name.replace("_", " ")) for choice in ClassEnum])
    Comparable = models.BooleanField(default=True)

class Function(models.Model):
    Id = ShortUUIDField(unique=True, primary_key=True, blank=False, editable=False)
    Name = models.CharField(max_length=50)
    Properties = models.ManyToManyField(Property, blank=True)

class Device(models.Model):
    Id = ShortUUIDField(unique=True, primary_key=True, blank=False, editable=False)
    Name = models.CharField(max_length=50)
    Parameters = jsonfield.JSONField(default="{}")
    Functions = models.ManyToManyField(Function, blank=True)

2 个答案:

答案 0 :(得分:0)

默认情况下,django已经以惰性模式进行了连接...因此,如果您需要它们,...如何使用

使用常规的ForeignKey(一对一或一对多关系)

class User(models.Models):
    ...
    attribute1 = models.CharField(max_lenght)

class Person(models.Models):
    user= models.ForeignKey(User)
    attribute2 = models.CharField(max_lenght)

class Student(models.Models):
    person = models.ForeignKey(Person)
    attribute3 = models.CharField(max_lenght)

for student in Student.objects.all():
    print(student.attribute3)
    print(student.person.attribute2)
    print(student.person.user.attribute1)

这样,当您使用外键进行操作时,您将达到所有联接

因此,在上面仅是有关django如何处理事情的一些信息

关于您的疑问,您可以这样做

...
result = []
for f in self.Functions.all():
    [result.append(p) for p in f.Properties.all()]
return result

答案 1 :(得分:0)

您可以这样写:

result = Properties.objects.filter(function__device=self)

因此,在这里,我们JOINPropertiesFunction之间使用多对多表,在Function和{{ 1}}。