python - Why can't uniqueness be enforced on Django ManyToMany field? -
i'm creating simple binary rating system website, study materials website summaries can rated +1 or -1.
i've defined manytomany fields between summary model , user model so:
users_rated_positive = models.manytomanyfield( user, blank=true, related_name='summaries_rated_positive') users_rated_negative = models.manytomanyfield( user, blank=true, related_name='summaries_rated_negative')
however obvious given user can not rate given summary more once.
i tried setting unique=true django doesn't seem let me that.
is there more optimal way store ratings aligns better intentions?
consider using manytomany through table.
class summary(models.model): user_ratings = models.manytomanyfield( 'user', blank=true, through='userrating', ) class userrating(models.model): user = models.foreignkey('user') summary = models.foreignkey('summary') is_positive = models.booleanfield() class meta: unique_together = ('user', 'summary')
then can query users reviewed summary positively like
summary.user_ratings.filter(is_positive=true) summary.user_ratings.filter(is_positive=false)
the unique_together
property ensures user can't review same summary twice.
you retain similar syntax using custom queryset. here's guess @ might like:
class summaryqueryset(models.queryset): def users_rated_negative(self): return self.user_ratings.filter(is_positive=false) def users_rated_positive(self): return self.user_ratings.filter(is_positive=true) class summary(models.model): user_ratings = models.manytomanyfield( 'user', blank=true, through='userrating', ) objects = summaryqueryset.as_manager()
now in-use syntax summary.users_rated_positive
a similar custom queryset user
give summaries_rated_positive
property, if needed too.
Comments
Post a Comment