Home:ALL Converter>django-simple-history how to get the related foreign key objects

django-simple-history how to get the related foreign key objects

Ask Time:2022-02-03T22:57:21         Author:Sardar Faisal

Json Formatter

I have a model named Order and another OrderItem. The OrderItem table has a foreign key to the Order table. Now I have the [simple-history][1] installed and setup on both the models. I try to get the Order history and also fetch related OrderItem from history using the related name on the OrderItem table but it returns an error:

AttributeError: 'HistoricalOrder' object has no attribute 'order_items'

Here is my Order and OrderItem table.

class OrderItem(models.Model):
    order = models.ForeignKey(
        "Order", on_delete=CASCADE, related_name="order_items"
    )
    content_type = models.ForeignKey(ContentType, on_delete=models.RESTRICT)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey("content_type", "object_id")
    history = HistoricalRecords()
    .......

class Order(models.Model):
    po_id = models.CharField(max_length=50, unique=True, blank=True, null=True)
    history = HistoricalRecords()
    .....

Following command gives me an order.

 order = Order.history.filter(id=102).first()

But if I run order.order_items.all() then I get the attribute error.

If I run the query on the actual model then I get the order_items by using below command.

Order.objects.get(id=102).order_items.all()

Is it possible to get the order_items from the history table in the same way as normal django models. And how can I do this to work.

Thank you. [1]: https://django-simple-history.readthedocs.io/en/latest/index.html

Author:Sardar Faisal,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/70973520/django-simple-history-how-to-get-the-related-foreign-key-objects
yy