Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is tuple being returned?

I have the following:

tableNumber = session.query(TABLE.TABLESNUMBER).filter_by(TABLESID=self.TABLESID).first()         
return str(tableNumber)

This is my TABLE class:

class TABLE(Base):

    ....   

    TABLESID = Column(Integer, primary_key=True)
    TABLESNUMBER = Column(Integer, nullable=False)

    ...

This is the output I am receiving:

(1L,)

In my mySQL database, all both values above are represented as ints.

I would just like 1 to be returned.


2 Answers

query().first() returns the first row. That's why a tuple is being returned. The query does not care that in the first row there is only 1 value, resulting in a tuple of length 1.

If you're sure the query will return only 1 scalar value, you can use scalar() instead of first(). Please read up the linked documentation.

edit: To get the first value in the first returned tuple, when the query may return multiple rows, you can either add order_by(...).limit(1) to the query and then use scalar(), or get the first row and and then explicitly convert the tuple to an int.

like image 122
Haleemur Ali Avatar answered Jun 22 '26 08:06

Haleemur Ali


first() and all() return 'tuple'

So,
session.query(TABLE.TABLESNUMBER).filter_by(TABLESID=self.TABLESID).first() returns its tuple including 'TABLESNUMBER'

If you want exactly one value (TABLESNUMBER)

You can use it. session.query(TABLE.TABLESNUMBER).filter_by(TABLESID=self.TABLESID).first().TABLESNUMBER

like image 36
Chase Choi Avatar answered Jun 22 '26 08:06

Chase Choi