0

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

Guet123
  • 3
  • 2
  • 1
    The question, as stated, is ambiguous. Because [the order of rows in an SQL table is ambiguous](https://stackoverflow.com/questions/10064532/the-order-of-a-sql-select-statement-without-order-by-clause), you need to specify a column to sort by (e.g. the primary key). – Nick ODell Oct 21 '21 at 15:15
  • Hi @NickODell, I'm new to so and don't know how to add third column to my table, but I have an ID column that is PK – Guet123 Oct 21 '21 at 15:19
  • In that case, you can use `.order_by('id')` in your queryset to put the results in order. – Nick ODell Oct 21 '21 at 17:27

1 Answers1

0

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

Felix Eklöf
  • 3,253
  • 2
  • 10
  • 27