[Django]-Update data in table which has foreign keys in Django

3👍

There are a few things that got me confused, but I think this is what you want:

# NOTE: store is the store instance you want the price to be associated with
# For example, store = store_table.objects.get(pk=...)
# And you could iterate through every store object and CREATE the price
# for that store using the code below.  Again, this does not UPDATE,
# this CREATES a new price_table object for that store_table object.

update_models = price_table(
            store_id=store
            dates=dates,
            price=price
        )
update_models.save()

Why am I confused? The above code will CREATE a new price_table object, not update it. If you had a price_table object already that you wanted to UPDATE, that is change, then it would ALREADY be associated with a store, in which case you could do this:

# update_models here would be an object you FIND, not CREATE, for example,
# update_models = price_table.objects.get(pk=...)

update_models.dates = dates
update_models.price = price
update_models.save()

Remember, you can’t update a MODEL, you update an INSTANCE of a model. The model is just a template for creating instances or objects based on that model. You do not update the template, you update the instance. Now, if the INSTANCE of your price_table does NOT have a sales_table associated with it yet (you have, after all, default=None for the store_id), then you could modify the above to:

# Again, here, update_models will be a price_table INSTANCE you find, and
# store would be the store_table object you find, i.e.
# store = store_table.objects.get(pk=...)
# where pk is the primary key of the store you want the price associated with

update_models.store_id = store
update_models.dates = dates
update_models.price = price
update_models.save()

There was something else that got me confused. For classes you want to use Pascal case, that is, instead of store_table, write Store, instead of price_table, write Price (they are all tables, after all).

This is another point that confused me. Price should be some kind of number, correct? Then why have it as a CharField? Might it not be better to use a DecimalField instead?

Hope this helps.

Leave a comment