0

I could get a single value from MySQL database on Django(Python). However, it looks like the code are too long. Is there a way to make it short codes? Thanks

    result = cursor.execute("SELECT idx FROM myapp_profile WHERE full_name = '"+fullname+"' AND birthday = '"+birthday+"' LIMIT 1")
    if result:
        #create session
        col_names = [desc[0] for desc in cursor.description]
        while True:
            row = cursor.fetchone()
            if row is None:
                break
            resultsList = dict(izip(col_names, row))

        profile_idx = resultsList["idx"]

2 Answers 2

3

You can use the combination of the only() and the first() methods:

profile = Profile.objects.only('idx').filter(full_name=full_name,
                                             birthday=birthday).first()
profile_idx = profile.idx if profile else None

Another solution is to use the values_list():

indexes = list(Profile.objects.filter(full_name=full_name, birthday=birthday) 
                              .values_list('idx', flat=True)[:1])
profile_idx = indexes[0] if indexes else None
Sign up to request clarification or add additional context in comments.

Comments

0

It would depend on what your exactly trying to do for instance if your just looking for people with birthdays today or if your lookimg for someones birthday. That make sence? So if your just looking for people with todays bday you should create a variable with todays date amd look for the user with that date. I guess what im asking is what are youyou trying to do because that will depend on query magic you would use.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.