Hi all,

I'm encountering exceptions in a number of popular third-party Django 
libraries when upgrading from 1.8 to 1.11. The code path is typically 
`MyModel.objects.get_or_create(...)`, which causes 
`model._meta._property_names` to be checked (to make sure we're not 
querying/setting a property). The problem is, `_property_names` is 
implemented as follows:
    
# in django/db/models/options.py:
def _property_names(self):
    return frozenset({
       attr for attr in
       dir(self.model) if isinstance(getattr(self.model, attr), property)
    })

The problem is when a custom field installs a field descriptor on the model 
class (during `contribute_to_class()`), with a `__get__()` method like this:

class SomeFieldDescriptor(object):
    # ...
    def __get__(self, instance, type=None):
        if instance is None:
            raise AttributeError("Can only be accessed via an instance.")
        # ...

Libraries which install such descriptors include 
[django-fsm](https://github.com/kmmbvnr/django-fsm/blob/2d2eaee/django_fsm/__init__.py#L225)
 
and 
[django-jsonfield](https://github.com/dmkoch/django-jsonfield/blob/2.0.1/jsonfield/subclassing.py#L35).
 
I think the problem is that we can't assume that all results of 
`dir(model_class)` can be accessed via `getattr(model_class, attr)` without 
exception; indeed, the Python docs state (c.f. 
https://docs.python.org/2/library/functions.html#dir):

> Because dir() is supplied primarily as a convenience for use at an 
interactive prompt, it tries to supply an interesting set of names more 
than it tries to supply a rigorously or consistently defined set of names, 
and its detailed behavior may change across releases.

A potential fix would be to adjust the definition of `_property_names` like 
so:

def _property_names(self):
    attrs = []
    for attr in dir(self.model):
        try:
            if isinstance(getattr(self.model, attr), property):
                attrs.append(attr)
        except AttributeError:
            pass
    return frozenset(attrs)

Does this seem like a good solution, or even a problem worth solving?

Thanks!
-- Zack

-- 
You received this message because you are subscribed to the Google Groups 
"Django developers  (Contributions to Django itself)" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-developers+unsubscr...@googlegroups.com.
To post to this group, send email to django-developers@googlegroups.com.
Visit this group at https://groups.google.com/group/django-developers.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-developers/ec0e2506-4c4b-441f-b005-5623d6521ae3%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to