Gurus:
I have a very simple data model relating two different kinds of User
s via an Interaction
:
# myapp/models.py
class C1(models.Model):
user = models.ForeignKey(User)
class C2(models.Model):
user = models.ForeignKey(User)
class Interaction(models.Model):
c1 = models.ForeignKey(C1)
c2 = models.ForeignKey(C2)
date = models.DateField()
So, an Interaction
has a User
of class C1
, a User
of class C2
, and a date (in addition to the primary key, automatically an integer); a given pair of users can have many Interaction
s.
I populated the database with 2000 random User
s (1000 each class), and when I query the Interaction
the run time is too slow (about three seconds - unacceptable in production environment).
Is there something I can do to improve the run time of this search? Should I define the Interaction
differently?
Thanks.
If you'd like to store additional information related to your users, Django provides a method to specify a site-specific related model -- termed a "user profile" -- for this purpose.
To make use of this feature, define a model with fields for the additional information you'd like to store, or additional methods you'd like to have available, and also add a OneToOneField from your model to the User model. This will ensure only one instance of your model can be created for each User. For example:
# settings.py
AUTH_PROFILE_MODULE = 'myapp.UserProfile'
# myapp/models.py
class UserProfile(models.Model):
CLASS_CHOICES = (
(0, 'Yellow User'),
(1, 'Green User'),
)
user_class = models.IntegerField(choices=CLASS_CHOICES)
user = models.OneToOneField(User)
class Interaction(models.Model):
u1 = models.ForeignKey(User, related_name='u1s')
u2 = models.ForeignKey(User, related_name='u2s')
date = models.DateField()
Creating a new model and associated table for each User class seems not like good design.
You have used foreign keys to associate C1, C2
with Users
, and called this a one-to-many relationship . However, the relationship between Interaction
C1, C2
is not one-to-many because one Interaction
can be associated with many Users
, and one User
can also have many Interactions
associated with it. This is called a many-to-many relationship , and is represented in Django models using models.ManyToManyField
.
So try changing your models.py
file to -
class Interaction(models.Model):
ic1 = models.ManyToManyField(C1)
ic2 = models.ManyToManyField(C2)
date= models.DateField()
See if this helps...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.