Login

common model privacy

Author:
teepark
Posted:
July 31, 2007
Language:
Python
Version:
.96
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. Template tag - list punctuation for a list of items by shapiromatron 3 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 3 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 10 months, 1 week ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 11 months ago
  5. Help text hyperlinks by sa2812 11 months, 3 weeks ago

Comments

Please login first before commenting.