In this application, we need to store the data related to each movie and the movies' ratings from each user of the website. We set up three models:
class UserProfile(models.Model): user = models.ForeignKey(User, unique=True) array = jsonfield.JSONField() arrayratedmoviesindxs = jsonfield.JSONField() lastrecs = jsonfield.JSONField() def __unicode__(self): return self.user.username def save(self, *args, **kwargs): create = kwargs.pop('create', None) recsvec = kwargs.pop('recsvec', None) print 'create:',create if create==True: super(UserProfile, self).save(*args, **kwargs) elif recsvec!=None: self.lastrecs = json.dumps(recsvec.tolist()) super(UserProfile, self).save(*args, **kwargs) else: nmovies = MovieData.objects.count() array = np.zeros(nmovies) ratedmovies = self.ratedmovies.all() self.arrayratedmoviesindxs = json.dumps([m.movieindx for m in ratedmovies]) for m in ratedmovies: array[m.movieindx] = m.value self.array = json.dumps(array.tolist()) super(UserProfile, self).save(*args, **kwargs) class MovieRated(models.Model): user = models.ForeignKey(UserProfile, related_name='ratedmovies') movie = models.CharField(max_length=100) movieindx = models.IntegerField(default=-1) value = models.IntegerField() class MovieData(models.Model): title = models.CharField(max_length=100) array = jsonfield.JSONField() ndim = models.IntegerField(default=300) description = models.TextField()
The model MovieData
stores the data for each movie: title, description, and vector representation (ndim
is the dimension of the vector representation). MovieRated
records each movie rated by the user logged in (each object MovieRated
is associated with has a UserProfile
that utilizes the website). The UserProfile
model stores all the users that sign up to the website, so they can rate movies and receive recommendations. Each UserProfile
extends the default Django user model by adding the array
field, which stores all the movie's ratings from the user,
and the recsvec
field which stores his last recommendations: the save
function is overridden to fill the array
field with all the MovieRated
objects associated with the user (if the else
statement is true
), and to fill the lastrecs
field with the last recommendations (else if
statement). Note that the MovieRated
model has a UserProfile
foreign key with the related_name
equal to ratedmovies
: in the save
function of the UserProfile
model, self.ratedmovies.all()
refers to all the RatedMovie
objects that have the same UserProfile
value. The field arrayratedmoviesindxs
on the UserProfile
model records all the movies rated by the user and it is used by the API of the application.
To write these data structures on the database we need to run:
python manage.py makemigrations python manage.py migrate
18.118.198.81