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

Viewed 295

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

1 Answers
Related