views:

32

answers:

1

Hi, I have a model in django that have a boolean private/public attribute:

class TestModel(models.Model):
    name = models.CharField()
    is_public = models.BooleanField(default=False)

I want that every-time I query this model in an application it returns only public instances to the common user and all available instances to the super-user.

How and where I need to implement such functionality?

+3  A: 

You implement that logic at the view layer, probably with a custom manager.

Your manager would look something like this:

class PublicTestModelManager(models.Manager):
  def get_query_set(self):
    return super(PublicTestModelManager, self).get_query_set().filter(is_public = True)

Your model would look something like:

class TestModel(models.Model):
    name = models.CharField()
    is_public = models.BooleanField(default=False)
    objects = models.Manager() # The default manager.
    public_objects = PublicTestModelManager()

You could then write a function that picked the right manager:

def test_objects_for_user(user):
  if user.is_superuser:
    return TestModel.objects
  else:
    return TestModel.public_objects

Then in your view you could use:

test_objects_for_user(request.user).all()
Dominic Rodger
+1. A custom manager sounds like the right way to go.
Manoj Govindan
but then I still need to write if/else clause in every view, right?
dragoon
@dragoon - answer updated.
Dominic Rodger
Thanks, seems very complicated for me, I though there could be more simple solution)
dragoon