jazzband/django-simple-history

Same related_query_name(s) used in the Model and in the HistoricalModel foreign key(s)

scur-iolus opened this issue · 0 comments

Describe the bug

Let's assume that:

  • We have a model Foo,
  • We have another model Bar with a ForeignKey to Foo,
  • This ForeignKey has a related_query_name set to bar,
  • We register Bar with django-simple-history.

Then, both the initial and the historical model (Bar and HistoricalBar) use the same related_query_name. In other terms, queries like Foo.objects.filter(bar__isnull=False).count() might return inconsistent and unexpected results, getting the models Bar and HistoricalBar mixed up. In some similar cases, the initial reverse relation takes a back seat to the historical one.

To Reproduce

This repository contains a minimal reproducible example. In particular, see the models.py file with the set up described above and the initial migration file. Lines 58 and 97 of this migration file are commented to highlight the problem.

Expected behavior

Admittedly, it's recommended to use %(class)s in the related_query_name to avoid conflicts. But when this precaution is not taken, I think that either an error should be raised, or the default ForeignKey.related_query_name of an HistoricalModel should be something like historical_[initial_related_query_name], in order not to overwrite the initial reverse relation. The current behavior can lead to pesky bugs...

As a reminder, in similar situations, Django sometimes raises an exception fields.E305 (see here).

Screenshots

issue

Environment

  • Django Simple History Version: 3.4.0
  • Django Version: 4.2.7