Posted under » Python » Django on 24 May 2022
In Python, arrays are called lists. In anoneh, I will refer them as lists.
Initialise
cars=[]
Or straight away add some values.
cars = ["Ford", "Volvo", "BMW"]
Use the len() method to return the length of an array (the number of elements in an array) or query.
x = len(cars) 3
This is similar to PHP and django count()
To show a value
print(cars[2])
Looping to show all values
for x in cars: print(x)
You can use the append() method to add an element to an array.
cars.append("Honda")
To create an associative array, the brackets turn curly and arrow (in PHP) is colon.
af = {'ahmad' : 'WENDY', 'sollihin' : 'CHOOI LENG'}
Assuming you have a car associative array and wants just the model id (m_id field) sorted by car type in django
model_list = [] for mod in carass: model_list.append(mod.m_id) # use the model_list array carmod = cars.objects.filter(model__in=model_list).order_by('type')
Note that carass and cars are 2 separate tables or objects. The '__in' means the model is equal to the ids on the model_list array.
Somehow searching in arrays is quite forgiving. In the above cars example, it is a string, but below is integer so it doesn't matter if it's a number or string.
def takenqid(request): global le sid = request.user.id fresh = [518, 519, 520, 521, 523, 524] checkobj = Users.objects.filter(user_id=sid) taken=[] for gay in checkobj: taken.append(gay.resume_question_id) available = [] for element in fresh: if element not in taken: available.append(element) le = available[0] return le
What the above function does is to see if there are anything from the fresh array that is not already in taken array. If there is then append to the available array. Useful when you want to give people content that the person has not seen.
There are many ways to get unique records. in Python. This is just one way.
query .... sid=[] for pet in query: sid.append(pet.student_id) unique_list = list(dict.fromkeys(sid)) for pet in unique_list: print(pet)
Removing Array Elements by pop or remove
cars.pop(1) #2nd element cars.remove("Volvo")
For PHP array.
See also Show all rows in Django template.