Skip to content Skip to sidebar Skip to footer

AutoField Should Be Present But It's Not (django)?

Looking at: https://docs.djangoproject.com/en/3.1/ref/models/instances/#django.db.models.Model.save For convenience, each model has an AutoField named id by default unless you exp

Solution 1:

The first positional parameter is still the id. Whether that is an AutoField or not is irrelevant. Especially since Django also uses the constructor to load model objects from the database, and sometimes you want to specify the id, because you want to update an object.

You can use None if you do not want to specify the primary key:

#                ↓ use None such that the database will provide an id
coin = Currency(None, coin_key, crypto_coins_prices[coin_key]['usd'], timezone_now)

but regardless, the is still "unstable", since adding an extra field somewhere results in the fact that the order of the parameters will change. It is better to use named parameters:

coin = Currency(
    currency_name=coin_key,
    currency_value_in_dollars=crypto_coins_prices[coin_key]['usd'],
    currency_value_in_dollars_date=timezone_now
)

Note: Django's DateTimeField [Django-doc] has a auto_now_add=… parameter [Django-doc] to work with timestamps. This will automatically assign the current datetime when creating the object, and mark it as non-editable (editable=False), such that it does not appear in ModelForms by default.


Post a Comment for "AutoField Should Be Present But It's Not (django)?"