Opened 12 years ago

Closed 10 years ago

#18389 closed Bug (fixed)

Field type attributes not permitted on models

Reported by: john.arnfield@… Owned by: drtyrsa
Component: Database layer (models, ORM) Version: 1.4
Severity: Normal Keywords:
Cc: Triage Stage: Accepted
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

I have a situation where I need to reference a django model-field type in my models, something that would look like the following:

from django.db import models
class MyModel(models.Model):
  referenced_field = models.CharField
  # ... field declarations here

The omission of parenthesis on the CharField is intentional. I do not want to create a field on this model, I simply need to reference a field type that this model is associated with.

Unfortunately this causes a type error:

TypeError: Error when calling the metaclass bases
    unbound method contribute_to_class() must be called with AutoField instance as first argument (got ModelBase instance instead)

This is down to ModelBase.add_to_class being overly naive in the way it calls contribute_to_class (it uses hasattr to check for things that define contribute_to_class, but doesn't care if they're types or objects).

One solution to this problem would be to change the class attribute in to a classmethod, but the problem seems a little unnecessary and feels like it should be cleaned up regardless. Unfortunately, I'm not sure what the ideal solution would be for this case, else I'd already have submit a patch.

Change History (5)

comment:1 by anonymous, 12 years ago

Type: UncategorizedBug

comment:2 by anonymous, 12 years ago

Maybe the resolution here is that anything with contribute_to_class will be tried for add to class. This could be solved if the contribute_to_class method must be a bound method by checking for value.contribute_to_class.__self__ is not None.

comment:3 by Aymeric Augustin, 12 years ago

Triage Stage: UnreviewedAccepted

comment:4 by drtyrsa, 10 years ago

Has patch: set
Owner: changed from nobody to drtyrsa
Status: newassigned

Here is pull request: https://github.com/django/django/pull/2658

I don't check that the method is bound, I check that the object that has this attribute is an instance, not a class, I think it's more tranparent and has this case covered.

comment:5 by Tim Graham <timograham@…>, 10 years ago

Resolution: fixed
Status: assignedclosed

In 1be03aff5c24e902b89503dda32891aa4881579e:

Fixed #18389 -- Fixed the way contribute_to_class is called

Now this method is only called only if the object is an instance.
This allows to have field classes as model class attributes.

Note: See TracTickets for help on using tickets.
Back to Top