我有两个型号:
class Company(models.Model):
...
class Supplier(models.Model):
company = models.ForeignKey(Company, null=True, related_name="suppliers")
如何让所有公司与其相关供应商合作?
我试过了:
Company.objects.prefetch_related('suppliers')
Company.objects.prefetch_related('supplier_set')
Company.objects.prefetch_related('suppliers').all()
...
我做错了什么?
谢谢
答案 0 :(得分:2)
prefetch_related
just adds the SQL query让供应商在company.suppliers.all()
执行Company.objects.all()
时,不会在companies = Company.objects.all().prefetch_related('suppliers')
for company in companies:
# Does not require a new SQL query
suppliers = company.suppliers.all()
之上发生另一次SQL命中。您可以在此后访问供应商:
# Some Data. All rows have an NA but not all columns
df <- data.frame(col1 = c(NA, 2, 3, 4),
col2 = c(1, NA, 3, 4),
col3 = c(1, 2, NA, 4),
col4 = c(1, 2, 3, NA),
col5 = c(1, 2, 3, 4))
# test whether an NA is present in each row
apply(df, 1, function(x) {sum(is.na(x)) > 0})
[1] TRUE TRUE TRUE TRUE