Django通过PHP插入数据库

发布于 2025-02-07 03:16:37 字数 238 浏览 1 评论 0原文

目前,我总是用Django创建了后端的结构和逻辑。但是,当我将数据插入数据库时​​,我会直接通过HTTP请求将数据插入到PHP脚本中。 当项目增长时,它会变得非常凌乱。同样,从数据库到后端的时间戳总是有并发症。

我想消除所有这些缺陷,但是如果我只能向Django中的某个视图提出请求,则找不到任何好示例,其中包含我想输入数据库中的所有信息。 Django和数据库在同一台计算机上,但是插入的数据来自不同的设备。 也许您可以给我一个提示如何进一步搜索

For now I always created the structure and logic of my backend with Django. But when I insert data into the database I alwas did that directly via a http request to a php script.
When the projects grows it is getting pretty messy. As well, there were always complications with timestamps from the database to the backend.

I want to eliminate all these flaws but could not find any good example If I could just make a request to a certain view in Django, containing all the information I want to put into the database. Django and the database are on the same machine, but the data that is being inserted comes from different devices.
Maybe you could give me a hint how to search further for this

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

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

发布评论

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

评论(1

不爱素颜 2025-02-14 03:16:37

您可以创建一个Python脚本并运行它。
假设您有一个Virtualenv,请确保必须激活。并将其放在您的Django项目的根源中。

#!/usr/bin/env python
import os

import django


os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myapp.settings")
django.setup()

# Import after setup, to ensure they are initiliazed properly.
from myapp.models import MyModel, OtherModel


if __name__ == "__main__": 
    # Create your objects.
    obj = MyModel.objects.create(some_value="foo")
    other_obj = OtherModel.objects.create(title="Bar", ref=obj)

您还可以使用交易来确保其仅承担全部或全部。

from django.db import transaction

with transaction.atomic():
    obj = MyModel.objects.create(some_value="foo")
    other_obj = OtherModel.objects.create(title="Bar", ref=obj)

如果其中一个作品失败,一切都会倒退。这样可以防止最终获得半填充或损坏的数据库。

You can just create a python script and run that.
Assuming you have a virtualenv, ensure you have to activated. And put this in the root of your Django project.

#!/usr/bin/env python
import os

import django


os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myapp.settings")
django.setup()

# Import after setup, to ensure they are initiliazed properly.
from myapp.models import MyModel, OtherModel


if __name__ == "__main__": 
    # Create your objects.
    obj = MyModel.objects.create(some_value="foo")
    other_obj = OtherModel.objects.create(title="Bar", ref=obj)

You can also use transaction to ensure it only commits all or none.

from django.db import transaction

with transaction.atomic():
    obj = MyModel.objects.create(some_value="foo")
    other_obj = OtherModel.objects.create(title="Bar", ref=obj)

Should one of the creations fail, everything is rolled back. This prevent from ending up with a half filled or corrupt database.

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