[英]Django query many objects in many
有沒有一種查詢方法可以在Django模型中執行以下操作(例如加入SQL)?
result = []
for f in self.Functions.all():
result = result + list(f.Properties.all())
return result
其中self
是一個Device
對象
楷模
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)
默認情況下,django已經以懶惰模式進行了連接...因此,如果您需要它們,...如何使用它
使用常規的ForeignKey(OneToOne或OneToMany關系)
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
您可以這樣寫:
result = Properties.objects.filter(function__device=self)
所以在這里,我們將Properties
和Function
之間的多對多表以及Function
和Device
之間的多對多表JOIN
在一起。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.