Home > OS >  Django Table forward fill missing values
Django Table forward fill missing values

Time:10-22

I have a table like this:

A B
a row
row
row
row
b row
row
row
c row
... ....

How can I fill in missing values like forward fill in Pandas data frame using Django ORM query?

PS: I have an ID column which is unique

CodePudding user response:

Assuming, that the table is sorted by primary key.

If this is just a one-off you could do something like this. It will probably take a very long time if you have a very large table. To actually run in you can use the django shell or django management command.

latest_a = None
max_id = MyModel.objects.last().id

for i in range(1, max_id   1):
    try:
        instance = MyModel.objects.get(pk=i)
    except MyModel.DoesNotExist:
        continue
    if instance.a == None and latest_a:
        instance.a = latest_a
        instance.save()
    else:
        latest_a = instance.a

  • Related