Opened 4 years ago

Last modified 4 years ago

#17043 new Bug

Model subclass field named the same as one of the parent model subclasses clashes

Reported by: charettes Owned by: nobody
Component: Database layer (models, ORM) Version: 1.3
Severity: Normal Keywords:
Cc: Triage Stage: Accepted
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

The following model inheritance should raise a warning on model validation:

from django.db import models

class A(models.Model):
    pass

class B(A):
    pass

class C(A):
    b = models.BooleanField()

print A.b
#<django.db.models.fields.related.SingleRelatedObjectDescriptor object at 0x1b08e10>
print B.b
#<django.db.models.fields.related.SingleRelatedObjectDescriptor object at 0x1b08e10>
print C.b
#<django.db.models.fields.related.SingleRelatedObjectDescriptor object at 0x1b08e10>

C.objects.create(b=False)
#ValueError: Cannot assign "False": "C.b" must be a "B" instance.

Took me some time before figuring out what was happening. Feel free to rename the ticket with a more descriptive title.

Is there a reason why the RelatedObjectDescriptor is also added to the subclasses of A and not only the parent model? Lets say I have a c = C instance, theres no way c.b might return something, only a = A might do?

Change History (1)

comment:1 Changed 4 years ago by lukeplant

  • Needs documentation unset
  • Needs tests unset
  • Patch needs improvement unset
  • Triage Stage changed from Unreviewed to Accepted

The RelatedObjectDescriptor is not added to the subclasses - subclasses simply inherit descriptors by Python's normal inheritiance mechanism. Fixing this might be infeasible.

However, a validation warning ought to be possible, and accepting on that basis.

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