Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django model: Filtering by user, always

How do I achieve the following....

Every time the points object is displayed in a template it must always be filtered by the current user. So, within the model I tried the code below.

Is this possible? how can I achieve the above?

Models.py

from django.db import models
from django.contrib.auth.models import User


POINTS_PENDING, POINTS_ADDED, POINTS_DEDUCTED, ORDER_PROCESSING = range(4)
STATUS_OPTIONS = (
    (POINTS_PENDING, ('Pending')),
    (POINTS_ADDED, ('Added')),
    (POINTS_DEDUCTED, ('Deducted')),
    (ORDER_PROCESSING, ('Processing')),
    )


class PointsManager(models.Manager):

    def points_list(self,User):
        list = Points.objects.filter(points_user=User).exclude(status=ORDER_PROCESSING)
        return list


class Points (models.Model):
    user = models.ForeignKey(User)
    points = models.IntegerField(verbose_name=("Points"), default=0)
    created = models.DateTimeField(("Created at"), auto_now_add=True)
    updated = models.DateTimeField(verbose_name=("Updated at"), auto_now=True)

    objects = PointsManager()
like image 373
Prometheus Avatar asked Dec 25 '12 00:12

Prometheus


1 Answers

you could ensure that your views have a user by using

@login_required decorator

then you could could query for points by user in your view

user_points = Points.objects.filter(user=request.user)

or using the reverse FK lookup

request.user.points_set.all()

like image 96
dm03514 Avatar answered Sep 29 '22 20:09

dm03514