开发者

Django design question

开发者 https://www.devze.com 2023-01-15 02:00 出处:网络
I have a model in django that have a boolean private/public attribute: class TestModel(models.Model): name = models.CharField()

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.

H开发者_开发技巧ow and where I need to implement such functionality?


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()
0

精彩评论

暂无评论...
验证码 换一张
取 消