Login

common model privacy

Author:
teepark
Posted:
July 31, 2007
Language:
Python
Version:
.96
Tags:
models querysets
Score:
1 (after 1 ratings)

A BooleanField indicating privacy is common on models, but the name of the field and whether the field being True indicates private or public both may change across models. If there is more than one potentially private model, a common interface is needed. A commonly-named method would do the job with [a for a in MyModel.objects.all() if not a.is_private()], but it would still retrieve private instances from the database only to filter them out.

This approach puts the name of the privacy field and whether that field being True indicates private or public in a tuple attribute of the model class. A chainable method is added to all QuerySet objects.

example use:

class MyModel(models.Model):

is_public = models.BooleanField(default=True)

# ...

privacy_field = ("is_public", False)

>>> publicMyModels = MyModel.objects.all().exclude_private() >>> values = publicMyModels.values()

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
def exclude_private(self):
    """filter based on 'privacy_field' model class attribute

    'privacy_field' is a two-tuple whose first item is the name of a
    BooleanField and whose second item is a bool which is True if
    '<privacy_field[0]> == True' indicates private (such as a field 'is_private')
    """
    if not hasattr(self.model, "privacy_field"):
        return self

    privacy_field = self.model.privacy_field
    return self.exclude(**{privacy_policy[0]: privacy_field[1]})

from django.db.models import QuerySet
QuerySet.exclude_private = exclude_private

More like this

  1. FieldLevelPermissionsAdmin by buriy 7 years, 8 months ago
  2. Custom managers with chainable filters by itavor 7 years, 4 months ago
  3. FieldAccessForm (per-field user access for forms derived from models) by Killarny 6 years, 7 months ago
  4. PositionField by jpwatts 6 years, 10 months ago
  5. Django & cache headers by ludvig.ericson 7 years, 10 months ago

Comments

Please login first before commenting.