python - Two-way querying in Django without circular reference -
let's have 2 models: post
, category
. each post
has category_id
.
getting post's category straightforward: post.category
. if want posts category? suppose do
def posts(self): return post.filter(category__pk=self.id)
but if post
model , category
model in separate files? because post
, category
require each other, end circular reference.
maybe solution put post
, category
same file. if app has 50 different models, many of them quite large, in separate files? should combine post
, category
1 file , leave others separate? should combine 50 models 1 gigantic file?
i'm hoping find 1 of 2 things:
- an answer problem doesn't involve combining files
- a good, logical reason grouping models same file 1 another. models related extent, draw line far grouping goes? if draw line foreign keys, models end in same file.
you can refer models name (i.e., string) rather actual object. in separate applications? in case can refer them using dot notation described in documentation on foreignkey:
#in mysite/categories/models.py class category(models.model): ... #in mysite/posts/models.py class post(models.model): category = models.foreignkey('categories.category')
you can import model within function, rather @ top of file. avoid circular references:
def posts(self): posts.models import post return post.filter(category__pk=self.id)
Comments
Post a Comment