peewe basic and join queries

Posted under » MySQL » Python on 25 Aug 2023

< From peewee intro

It is similar to django api

For single record use get.

danial = display_student.select().where(display_student.id == '1').get()
danial = display_student.get(display_student.id == '1') #alt
print(danial.title)

Sometimes it is best to verify if the query is empty of not

query = display_student.select().where(display_student.student_id == '21')
if not query:
    print("You have nothing!")
else :
    print("Yass queen")

It is also a good idea to avoid the 'TermsDoesNotExist: Instance matching query does not exist:' error by using try

for pet in votes:
    try:
        danial = display_student.select().where(display_student.student_id == '21')
    except danial.DoesNotExist:
        print("You have nothing!")
    else:
        print(danial.choice_text)

To quickly view the rows, ask Peewee to return the rows as dictionaries.

for row in display_student.select(display_student.title, auth_user.username).join(auth_user).dicts().where(auth_user.username == 'danial'):
     print(row)

{'title': 'Differentiate \\(\\sqrt[3]{x}\\)...', 'username': 'danial'}
{'title': 'Find \\(\\frac{d}{dx}(\\frac{1}{x})\\)', 'username': 'danial'}
{'title': 'Find \\(\\frac{d}{dx}((3x-4)\\cos x)\\)', 'username': 'danial'}

In the peewee intro there is a foreign-key from display_student to auth_user, and we have selected fields from both models. Peewee uses ForeignKeyField to define foreign-key relationships between models. Every foreign-key field has an implied back-reference, which is exposed as a pre-filtered Select query using the provided backref attribute.

Now we’ll leave off the call to “.dicts()” and return the rows as Tweet objects. Notice that Peewee assigns the username value to (tweet.student_id.username – NOT tweet.username! Because there is a foreign-key from display_student to auth_user, and we have selected fields from both models, Peewee will reconstruct the model-graph for us:

for tweet in display_student.select(display_student.title, auth_user.username).join(auth_user):
     print(tweet.student_id.username, '->', tweet.title)

danial -> Differentiate \(\sqrt[3]{x}\) with respect to \(x\).
danial -> Find \(\frac{d}{dx}(\frac{1}{x})\)
danial -> Find \(\frac{d}{dx}((3x-4)\cos x)\)

Getting the last row of a query »

web security linux ubuntu python django git Raspberry apache mysql php drupal cake javascript css AWS data