AutoField应该存在,但不是(django)吗? [英] AutoField should be present but it's not (django)?

查看:30
本文介绍了AutoField应该存在,但不是(django)吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看着:

https://docs.djangoproject.com/zh-CN/3.1/ref/models/instances/#django.db.models.Model.save

为方便起见,每个模型默认都有一个名为id的自动字段除非您在自己的字段中明确指定primary_key = True模型.有关更多详细信息,请参见AutoField文档.

For convenience, each model has an AutoField named id by default unless you explicitly specify primary_key=True on a field in your model. See the documentation for AutoField for more details.

https://docs.djangoproject.com/en/3.1/topic/db/models/

很明显,一个对象总是有一个ID.我有一个模型:

it seems clear that an object always has an id. I have a model:

class Currency(models.Model):
    currency_name = models.CharField(max_length=100)
    currency_value_in_dollars = models.FloatField()
    currency_value_in_dollars_date = models.DateField()

    def __str__(self):
        return self.currency_name

我已迁移为:

operations = [
    migrations.CreateModel(
        name='Currency',
        fields=[
            ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
            ('currency_name', models.CharField(max_length=100)),
            ('currency_value_in_dollars', models.FloatField()),
            ('currency_value_in_dollars_date', models.DateField()),
        ],
    ),

,并且在尝试将条目添加到数据库时,例如:

and when trying to add entries to the db like:

def update_coins_table():
    if not do_greeting():
        print("Gecko crypto board not reachable. Db setup")
        return

    crypto_coins_prices = cg.get_price(ids=coins_ids_str, vs_currencies='usd')
    timezone_now = timezone.now()
    for coin_key in crypto_coins_prices:
        coin = Currency(coin_key, crypto_coins_prices[coin_key]['usd'], timezone_now)
        coin.save()

行:

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

给予:

unable to get repr for <class 'manage_crypto_currency.models.Transaction'> 

coin.save()

失败.如果我将相关行替换为:

fails. If I replace the line in question with:

coin = Currency(1, coin_key, crypto_coins_prices[coin_key]['usd'], timezone_now)

有效.id不应该自动递增吗?

it works. Shouldn't the id auto increment?

最后一行始终会覆盖前一行,最后只存储一个条目.

The last line always overwrites the previous and only one entry gets stored in the end.

推荐答案

第一个 positional 参数仍然是 id .是否为 AutoField 无关紧要.特别是由于Django还使用构造函数从数据库中加载模型对象,有时您想要指定id,因为您想 update 一个对象.

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.

如果您不想指定主键,则可以使用 None :

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)

但是不管怎样,它仍然是不稳定的",因为在某处添加额外的字段导致参数顺序将改变的事实.最好使用 named 参数:

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
)


注意:Django的 <代码> auto_now_add =… 参数[Django-doc] 使用时间戳.这将自动分配当前日期时间创建对象时,将其标记为不可编辑( editable = False ),例如默认情况下它不会出现在 ModelForm s中.

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.

这篇关于AutoField应该存在,但不是(django)吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆