Introduce class_plural %-substitution placeholder for related_name of ForeignKey/ManyToManyField
|Reported by:||puxlit||Owned by:||nobody|
|Component:||Database layer (models, ORM)||Version:||master|
|Severity:||Normal||Keywords:||related_name, ManyToManyField, ForeignKey, abstract base class|
|Cc:||Triage Stage:||Design decision needed|
|Has patch:||yes||Needs documentation:||no|
|Needs tests:||no||Patch needs improvement:||yes|
Django 1.2 introduced two %-substitution placeholders, %(class)s and %(app_label)s, to work around uniqueness issues when a custom related_name for a ForeignKey or ManyToManyField defined in an abstract base class is inherited by multiple child classes.
Quoting from Django's models documentation, "It's suggested ![...] that the name of a ManyToManyField ![...] be a plural describing the set of related model objects." Given the nature of a ManyToManyField, it may be preferable to reciprocate this pluralized field naming style through related_name. By introducing a third %-substitution placeholder, %(class_plural)s, this can be accomplished.
Consider the following snippet:
class Tag(models.Model): slug = models.SlugField(max_length=63, unique=True) class Post(models.Model): slug = models.SlugField(max_length=127, unique=True) tags = models.ManyToManyField(Tag, related_name='%(class_plural)s') # docs suggest related_name='%(app_label)s_%(class)s_related' class Meta: abstract = True class Entry(Post): title = models.CharField(max_length=255) content = models.TextField() class Meta: verbose_name_plural = 'entries' class Event(Post): summary = models.CharField(max_length=255) start_date = models.DateTimeField()
Arguably, tag.entries and tag.events are more semantic than either tag.entry_set and tag.event_set or tag.appname_entry_related and tag.appname_event_related.
Ultimately, the introduction of a %(class_plural)s %-substitution placeholder provides greater flexibility when designing models with abstract base classes and ForeignKeys or ManyToManyFields.
Change History (10)
Changed 4 years ago by puxlit
comment:1 follow-up: ↓ 4 Changed 4 years ago by anonymous
- Needs documentation unset
- Needs tests unset
- Patch needs improvement unset
comment:3 Changed 3 years ago by lrekucki
- Patch needs improvement set
- Triage Stage changed from Unreviewed to Design decision needed