Opened 4 months ago
Closed 4 months ago
#35641 closed New feature (wontfix)
Pattern matching on model objects
Reported by: | Johan Dahlin | Owned by: | |
---|---|---|---|
Component: | Database layer (models, ORM) | Version: | 5.0 |
Severity: | Normal | Keywords: | |
Cc: | Johan Dahlin | Triage Stage: | Unreviewed |
Has patch: | no | Needs documentation: | no |
Needs tests: | no | Patch needs improvement: | no |
Easy pickings: | no | UI/UX: | no |
Description (last modified by )
It would be nice if I could use pattern matching on Django model fields, this is especially important in context where I don't know what the model is, for example in a global post_save() handler where I want to do some specific logic based on a subclass.
class Person(Model): name = TextField(...) age = IntegerField(...) class Company(Model): address = TextField(...)
I would then be able to do
@receiver(pre_save) def pre_save(sender, instance, ....): # model comes in via signals or some other way, we don't know which subclass it is match model: # equivalent to isinstance(model, Person) and model.age > 10: case Person(age) if age> 10: .... # equivalent to isinstance(model, Company) and model.name.endswith('Street') case Company(address) if name.endswith('Street'): .... # or just extract and return a value case Person(name): return name
Happy to create a PR if this is interesting.
Change History (5)
comment:2 by , 4 months ago
Description: | modified (diff) |
---|
comment:3 by , 4 months ago
Description: | modified (diff) |
---|
comment:4 by , 4 months ago
I think we'd have to see a PR and how invasive it is to implement before taking a decision here. I personally only see marginal readability gains in the example you provided so I'm skeptical that's worth the complexity.
comment:5 by , 4 months ago
Resolution: | → wontfix |
---|---|
Status: | new → closed |
Hello Johan, welcome to the Django Community! Nice to see you again.
I personally like your proposal, but since Django is a community driven project, there is a established procedure to request new features which requires first gathering community consensus so then a ticket can be accepted. To do that, please consider starting a new conversation on the Django Forum, where you'll reach a wider audience and likely get extra feedback.
I'll close the ticket for now, but if there is a community agreement for the feature request, you are welcome to come back to the ticket and point to the forum topic, so we can then re-open it. For more details, please see the documented guidelines for requesting features.
Thanks!
I removed an earlier comment about a simple/straight-forward implementation using a @property but it won't work as, match_args needs to be a tuple and cannot be a property, so my suggested implementation above is too simplistic. I real one would have to be a bit more involved and generate the values and create a tuple inside the models metaclass.