Differences
This shows you the differences between two versions of the page.
python_wiki:django_api [2018/08/04 00:17] billdozor [Save Objects] |
python_wiki:django_api [2019/05/25 23:50] |
||
---|---|---|---|
Line 1: | Line 1: | ||
- | ====== Django API ====== | ||
- | |||
- | **General Information** | ||
- | |||
- | Interacting with the Django Python API. | ||
- | |||
- | **Checklist** | ||
- | * [[django_install|Django Installed]] | ||
- | * [[django_configuration|Django Configured]] | ||
- | |||
- | ---- | ||
- | |||
- | ====== Imports ====== | ||
- | |||
- | Imports and settings to add to your Python script in order to use your Django App's built in API. | ||
- | |||
- | \\ | ||
- | Import and Settings | ||
- | <code python> | ||
- | # | ||
- | |||
- | # Required module for sys.path.append | ||
- | import sys | ||
- | # Required module for os.environ | ||
- | import os | ||
- | |||
- | # Import Django WSGI App Loading capabilities | ||
- | from django.core.wsgi import get_wsgi_application | ||
- | |||
- | ##- Configure Django Settings to point to your App -## | ||
- | # sys.path = where manage.py is | ||
- | sys.path.append('/ | ||
- | |||
- | # Settings Module = projectname.settings | ||
- | os.environ[" | ||
- | application = get_wsgi_application() | ||
- | |||
- | # Import Django App Model (from ' | ||
- | from myapphere.models import AssetEntry | ||
- | </ | ||
- | |||
- | ---- | ||
- | |||
- | ====== Using Your Apps API ====== | ||
- | |||
- | Different ways to get your app data. | ||
- | |||
- | ===== Load Objects ==== | ||
- | |||
- | Objects can now be retrieved just like in views.py. | ||
- | <code python> | ||
- | # Load all assets (just like in views.py) | ||
- | asset_list = AssetEntry.objects.order_by(' | ||
- | |||
- | # Print all names (see your models.py for available fields) | ||
- | for node in asset_list: | ||
- | print(node.asset_name) | ||
- | </ | ||
- | |||
- | ===== Save Objects ==== | ||
- | |||
- | Create a new object and then save it to the database. | ||
- | <code python> | ||
- | # Set variables that will be used to create a new object | ||
- | new_name = " | ||
- | new_type = " | ||
- | new_description = "API Added Server" | ||
- | new_env = " | ||
- | new_os = " | ||
- | new_hardware = " | ||
- | |||
- | # Create the new object | ||
- | new_entry = AssetEntry(asset_name = new_name, asset_type = new_type, asset_description = new_description, | ||
- | |||
- | # Attempt to add new object to the database | ||
- | try: | ||
- | new_entry.save() | ||
- | print(" | ||
- | except: | ||
- | print(" | ||
- | </ | ||
- | |||
- | ---- | ||