I have the following model in Django:
from django.db import models
class User(models.Model):
pen_name = models.CharField(max_length=30)
email = models.EmailField()
activated = models.BooleanField()
def __unicode__(self):
return self.email + '-' + self.pen_name
class Original_Work(models.Model):
title = models.CharField(max_length=25)
summery = models.TextField()
user = models.ForeignKey(User)
date_published = models.DateField()
one_shot = models.BooleanField()
def __unicode__(self):
return self.title + '-' + self.user.email
class Chapter(models.Model):
work = models.ForeignKey(Work)
title = models.CharField(max_length=25)
order_number = models.IntegerField()
class Review(models.Model):
chapter = models.ForeignKey(Chapter)
work = models.ForeignKey(Work)
date_published = models.DateField()
class Work_Subscription(models.Model):
user = models.ForeignKey(User)
to_work = models.ForeignKey(Work)
class User_Subscription(models.Model):
user = models.ForeignKey(User, related_name='user_owner')
to_user = models.ForeignKey(User, related_name='user_to')
class Alert(models.Model):
title = models.CharField(max_length=60)
# add type
link = models.CharField()
class Book(models.Model):
title = models.CharField(max_length=50)
author = models.CharField(max_length=50)
def __unicode__(self):
return self.title
In summery/explanation each User “has” Works. Each work “has” chapters. Each chapter “has” a review and each review. There are other things as well but those don’t matter too my question. Right now, each thing that is “owned” has a Foreign Key to it’s “owner”. So a review has a foreign key to a chapter and chapter has a foreign key to a work and so on. My question is, what is a better way to do this? Right now, the server has to look through all of the reviews just to find which ones belong to a work. Is there someway to speed up/improve the look up process?
Edit: I will usually need to access data in the following direction User -> Work -> Chapter -> Review. Meaning that the server know what User and be asked to find all the works that user has done. This versus knowing the work and finding the user.
I’m assuming here that you intended to call your OriginalWork class simply “Work”. I’m also assuming we’re performing the query for the current visitor of the site. This should do the trick:
Also, you don’t need that redundant work field on your Review class, since Review keys to Chapter and Chapter keys to Work. i.e. you can easily get to Work from Review by going through Chapter – no need to have two ways to get there.
See the QuerySet API documentation for more.