Ric
Ric

Reputation: 103

Django Insert Data into database via php

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

Upvotes: 0

Views: 204

Answers (1)

The Pjot
The Pjot

Reputation: 1859

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.

Upvotes: 1

Related Questions