Skip to content
This repository has been archived by the owner on Mar 21, 2023. It is now read-only.

Working with Django Database Queries

Lindsay R. Silver edited this page Oct 2, 2015 · 1 revision

Writing a Django Database Query with Python

Specifically Looking at How to Import New Data from Existing Data

###Creating Aliases from Last Names

So, if you are already in the Friends Project folder in your terminal, to get to the python shell you would type:

python manage.py shell //allows you to run python on the Friends Asylum Project

Now you should see something like this, which indicates you are now running python:

>>>

Ok, so for this example, we are going to create the alias for all the Patient Entries models in the database from the existing last names we have for all the patients.

(You must already have created the Django model, and the two attributes: alias and last_name, for this example)

>>>from FriendAsylum.models import PatientEntry
>>>patient_list = PatientEntry.objects.order_by('patient_Info') //so this gets all the existing Patient Entries, and orders them alphabetically by the first_name that is part of Patient_Info
>>>def insert_alias(): //you must make a function which you will then run, spaces are very important here!
>>> for patient in patient_list: //(for every object in the patient_list we made)
>>> patient.patient_Info.alias = (patient.patient_Info.last_name[0:2]) //so I just insert the first two letters of the person's last name into alias
>>> patient.patient_Info.alias.save() // OR it be be that you need to use the .write() function
>>>insert_alias()
##Conclusion After you define and then call insert_alias, it will run all those instructions on the database and hopefully create aliases for all the patient entry objects. You can always use print statements to see what's been changed; for instance:
>>>print patient.patient_Info.alias //to check if there is now an alias for every patient