从 django shell 更新外键项目

发布于 2024-12-06 09:59:51 字数 2331 浏览 0 评论 0 原文

以下是 models.py:

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    belongs_to_user_category = models.ForeignKey(UserCustomCategory, null=True, blank=True)

class UserHistory(models.Model):
    date_time = models.DateTimeField()
    user = models.ForeignKey(UserProfile, null=True, blank=True)
    points_earned = models.DecimalField(max_digits=5, decimal_places=3)

很明显,userhistory 是 UserProfile 的外键。出于测试目的,我想更新名称以 a 开头的用户的点,

我在 python shell 中编写了以下代码:

from myapp.models import *
uobj = UserProfile.objects.all()
for i in uobj:
    if i.user.username[0] == 'a':
        b = UserHistory.objects.create(user=i)
        b.points_earned = random.random(10, 100)
        b.date_time = datetime.datetime.now()
        b.save()

我还尝试过 b = UserHistory.objects.get_or_create( user=i) 有同样的错误 我收到以下错误:

ERROR: An unexpected error occurred while tokenizing input
The following traceback may be corrupted or invalid
The error message is: ('EOF in multi-line statement', (160, 0))

ERROR: An unexpected error occurred while tokenizing input
The following traceback may be corrupted or invalid
The error message is: ('EOF in multi-line statement', (13, 0))

ERROR: An unexpected error occurred while tokenizing input
The following traceback may be corrupted or invalid
The error message is: ('EOF in multi-line statement', (63, 0))

ERROR: Internal Python error in the inspect module.
Below is the traceback from this internal error.

Traceback (most recent call last):
  File "/usr/local/lib/python2.6/dist-packages/IPython/ultraTB.py", line 667, in text
    locals,formatvalue=var_repr))
  File "/usr/lib/python2.6/inspect.py", line 875, in formatargvalues
    specs.append(strseq(args[i], convert, join))
  File "/usr/lib/python2.6/inspect.py", line 830, in strseq
    return convert(object)
  File "/usr/lib/python2.6/inspect.py", line 872, in convert
    return formatarg(name) + formatvalue(locals[name])
KeyError: 'connection'

IPython's exception reporting continues...

---------------------------------------------------------------------------
IntegrityError                            Traceback (most recent call last)


IntegrityError: (1048, "Column 'date_time' cannot be null")

Following is the models.py:

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    belongs_to_user_category = models.ForeignKey(UserCustomCategory, null=True, blank=True)

class UserHistory(models.Model):
    date_time = models.DateTimeField()
    user = models.ForeignKey(UserProfile, null=True, blank=True)
    points_earned = models.DecimalField(max_digits=5, decimal_places=3)

as is clear, userhistory is a foreign key to UserProfile. For the test purpose i wanted to update the points of the user whose name starts with a

I wrote the following code in the python shell:

from myapp.models import *
uobj = UserProfile.objects.all()
for i in uobj:
    if i.user.username[0] == 'a':
        b = UserHistory.objects.create(user=i)
        b.points_earned = random.random(10, 100)
        b.date_time = datetime.datetime.now()
        b.save()

i have also tried b = UserHistory.objects.get_or_create(user=i) with same error
and i get the following error:

ERROR: An unexpected error occurred while tokenizing input
The following traceback may be corrupted or invalid
The error message is: ('EOF in multi-line statement', (160, 0))

ERROR: An unexpected error occurred while tokenizing input
The following traceback may be corrupted or invalid
The error message is: ('EOF in multi-line statement', (13, 0))

ERROR: An unexpected error occurred while tokenizing input
The following traceback may be corrupted or invalid
The error message is: ('EOF in multi-line statement', (63, 0))

ERROR: Internal Python error in the inspect module.
Below is the traceback from this internal error.

Traceback (most recent call last):
  File "/usr/local/lib/python2.6/dist-packages/IPython/ultraTB.py", line 667, in text
    locals,formatvalue=var_repr))
  File "/usr/lib/python2.6/inspect.py", line 875, in formatargvalues
    specs.append(strseq(args[i], convert, join))
  File "/usr/lib/python2.6/inspect.py", line 830, in strseq
    return convert(object)
  File "/usr/lib/python2.6/inspect.py", line 872, in convert
    return formatarg(name) + formatvalue(locals[name])
KeyError: 'connection'

IPython's exception reporting continues...

---------------------------------------------------------------------------
IntegrityError                            Traceback (most recent call last)


IntegrityError: (1048, "Column 'date_time' cannot be null")

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

峩卟喜欢 2024-12-13 09:59:51

当您使用 Django 中默认模型管理器的 create 方法时,它还会尝试在数据库中创建该实例并将其保存。您可以通过两种方式做到这一点,但我将向您展示您可以使用您的方法做什么,这可能有助于理解。

首先,您需要创建一个 UserHistory 对象,但实际上并不保存它。这是通过简单地使用您想要的任何默认值实例化该模型类来完成的:

b = UserHistory(user=i)

之后,您可以设置其他属性。

b.points_earned = random.randint(10, 100)
b.date_time = datetime.datetime.now()
b.save()

这会起作用。因为您现在在设置 date_time 后保存 b

当然,有很多方法可以改进这一点,您可以简单地在一次调用中创建所有内容,因为您是在一个逻辑步骤中完成的,如下所示:

b = UserHistory.objects.create(
  user=i,
  points_earned=random.randint(10, 100),
  date_time=datetime.datetime.now(),
)

您可以通过阅读 DateField Django 文档,它将为您提供一些有关如何将默认日期设置为当前时间的提示。

希望这有帮助!

When you use the create method of the default model manager in Django, it will also attempt to create that instance into the database and save it. You can do this in two ways, but I'll show you what you can do with your approach, which may help in some understanding.

First, you will want to create a UserHistory object, but don't actually save it. This is done by simply instantiating that model class with any default values you'd like:

b = UserHistory(user=i)

After that, you can set the other attributes.

b.points_earned = random.randint(10, 100)
b.date_time = datetime.datetime.now()
b.save()

And this will work. Because you're now saving b after you've set the date_time.

There are ways to improve this of course, you can simply create everything in one call since you're doing it in one logical step, like so:

b = UserHistory.objects.create(
  user=i,
  points_earned=random.randint(10, 100),
  date_time=datetime.datetime.now(),
)

You can further improve this by reading the DateField docs for Django, which will give you some tips on how to set the default date to the current time.

Hope this helps!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文