我有一个看起来像的项目:
mysite/
|-- books
| |-- __init__.py
| `-- models.py
`-- org
|-- __init__.py
`-- models.py
书籍/ models.py:
from django.db import models
from mysite.org.models import Team
class BookSet(models.Model):
name = models.CharField(max_length=10)
team = models.ForeignKey(Team, related_name='booksets')
class Book(models.Model):
name = models.CharField(max_length=10)
book_set = models.ForeignKey(BookSet, related_name='books')
组织/ models.py:
from django.db import models
class Department(models.Model):
name = models.CharField(max_length=20)
class Team(models.Model):
name = models.CharField(max_length=20)
department = models.ForeignKey(Department, related_name='teams')
我想要达到的目的是获得部门的所有书籍,类似于:
class Department(models.Model):
name = models.CharField(max_length=20)
@property
def books(self):
# this won't work, is there any possible do it like this?
return self.teams.booksets.books()
我知道一种可能的方法是通过以下方式来实现:
from mysite.books.models import Book
class Department(models.Model):
name = models.CharField(max_length=20)
@property
def books(self):
return Book.objects.filter(book_set__team__department=self)
但是使用这种方法,我需要做一些棘手的事情,允许它们(books.models和org.models)循环互相导入。
所以我想知道是否有可能通过查询外键来查找部门的所有书籍,如下所示:
@property
def books(self):
# this won't work, is there any possible do it like this?
return self.teams.booksets.books()
答案 0 :(得分:3)
避免周期性导入的简单方法是将您的Department
模型设为:
class Department(models.Model):
name = models.CharField(max_length=20)
@property
def books(self):
from mysite.books.models import Book
return Book.objects.filter(book_set__team__department=self)
答案 1 :(得分:2)
我认为这样的事情会起作用:
class Department(models.Model):
name = models.CharField(max_length=20)
@property
def books(self):
booksets = list(team.booksets.all() for team in self.teams.all())
return list(bookset.books.all() for bookset in booksets)
但我没有一种简单的方法来测试它。
编辑:我忘记添加的另一种选择:
您可以使用字符串来引用ForeignKey定义中的模型。像这样:
class BookSet(models.Model):
name = models.CharField(max_length=10)
team = models.ForeignKey('org.Team', related_name='booksets')
然后在您的其他应用程序中,您可以自由导入books.models
有关详细信息,请参阅docs。
答案 2 :(得分:1)
你可以使用Django用来加载外键的相同机制,比如
user = models.ForeignKey('User')
怎么做:
from django.db.models.loading import get_model
Book = get_model('books', 'Book')
# which would achieve the same thing as
# from books.models import Book
get_model
定义为:
def get_model(self, app_label, model_name, seed_cache=True):
...