> I fully agree with you. This is generaly not a very good
> design, but i think we can do some exception for a very
> specific problems. For example, i found this very handy, when
> we have to support a multilingual db: getting the current
> language like this and use it to select the right values in db
> can save us a lot of work, and result in a more clear views
> code and template.

Bugged by the thread-local storage of the user, I've used a
classmethod to return the allowed objects, something like:

  def MyModel(Model):
    owner = ForeignKey(User)
    public = BooleanField()
    def for_user(cls, user):
      return cls.objects.filter(
        Q(owner__id = user.id) |
        Q(public=True)
        )
    for_user = classmethod(for_user)

and then in my view's code, simply use

  things = MyModel.for_user(request.user)

I'd like to try stunt I saw recently where I've got a decorative
model in the inheritance hierarchy that allows me to just define
standard field-names and then use multiple-inheritance to bring
in the method:

  class FilteredByUser(object):
    def for_user(cls, user):
      filters = Q(owner__id=user.id)
      if hasattr(cls, 'public'): #not sure on this syntax
        filters |= Q(public=True)
      return cls.objects.filter(filters)
    for_user = classmethod(for_user)

  def MyModel1(Model, FilteredByUser):
    owner = ForeignKey(User)
    public = BooleanField()

  def MyModel2(Model, FilteredByUser):
    owner = ForeignKey(User)

Tricky use of the Meta class might even be an elegant way to do
this without forcing the field-names to be "owner" and "public",
possibly allowing for definition of something like

  def MyModel3(Model, FilteredByUser):
    author = ForeignKey(User)
    published = BooleanField()
    class Meta:
      userfield = 'author'
      publicfield = 'published'

but patching FilteredByUser to allow for smart use of the Meta
class is left as an exercise for the reader (or at least until I
have some time to sit down and hack it :)

[regarding using thread-local variables to store the user]
> I know that it is not very good, but it is like evil, it is
> tempting :-)

+1 QOTW :)

-tkc




--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to