PROJECTS NOTES HOME

Random queries of django-orm

1 Random queries

from vessel.models import Vessel
x = Vessel.objects.get(vessel_code="1234567")
x
x.delete()
from base.models import Blog_post, Projects, Tag
Blog_post.objects.all()

pirmas = Blog_post.objects.first()
pirmas.tags
pirmas.tags.all()
pirmas.tags.first()
pirmas.tags.first().name
Blog_post.objects.filter(tags__name='emacs')
from deal.models import Deal
from django.contrib.auth.models import User
mng_user = User.objects.get(username="mng")
mng_user
<User: mng>
deal1 = Deal.objects.get(pk=2)
deal1
<Deal: Deal 1>
deal1.user
<User: dev>
deal1.user = mng_user
deal1.user
<User: mng>
deal1.save()

2 Modify a record in db with python example

2.1 Method 1

(venv) arvy@DESKTOP-AUDMJ7D:~/src/lifeapi$ python manage.py shell --settings=settings.development
Python 3.10.12 (main, Jun 11 2023, 05:26:28) [GCC 11.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)

import os
os.getcwd()

from lifeapi_apps.quiz_app.models import Question

Question.objects.all()

<QuerySet [<Question: Workout - YN>, <Question: Meditate - YN>, <Question: Miegojimas - Scale>]>

from django.contrib.auth.models import User

user_id_1 = User.objects.get(pk=1)

questions = Question.objects.all()

questions.update(created_by=user_id_1)

2.2 Method 2

start by this, do whatever you want then

python manage.py shell --settings=settings.development

from lifeapi_apps.quiz_app.models import Question, Answer
from django.contrib.auth.models import User

arvy_user = User.objects.get(username='arvy')
questions = Question.objects.filter(created_by=arvy_user)

for question in questions:
    print(question.description)

questions = Question.objects.all()
print(questions)

answers = question.answer_set.all()
print(answers)

question_description = "No Headache"
question = Question.objects.get(description=question_description)
question = Question.objects.get(description="No Headache", created_by=arvy_user)
print(question)

# think if you really want to rename this way!!! everything will be NO now.
Answer.objects.filter(question=question, answer="YES").update(answer="NO")

# better do a for loop like such:
# Get all answers related to the question
answers = Answer.objects.filter(question=question)
answers = Answer.objects.filter(question__description="Belly ache")
for answer in answers:
    if answer.answer == "YES":
        answer.answer = "NO"
    elif answer.answer == "NO":
        answer.answer = "YES"
    answer.save()

# rename a question
question_description = "aciukas"
question = Question.objects.get(description=question_description)
question = Question.objects.get(description="No Headache", created_by=arvy_user)
question.description = "No Alchohol"
question.save()

# Delete all answers related to the question
Answer.objects.filter(question=question).delete()