ContextSelect.distinct()#

relationalai
#ContextSelect.distinct(*args: Producer) -> Context

Selects the data to be returned by a query and returns the Context object whose .__enter__() method returned the ContextSelect object. Only distinct rows are returned. The query results are assigned to the Context object’s .results attribute. .distinct() may only be called in a query context.

Parameters#

NameTypeDescription
*argsProducer or Python string, number, date, datetime, or Boolean objects.The objects, properties, and other values to return in query results.

Returns#

A Context object.

Example#

Use .distinct() in a query context to select only distinct rows of data:

#import relationalai as rai


# =====
# SETUP
# =====

model = rai.Model("Books")
Book = model.Type("Book")

with model.rule():
    Book.add(title="The Illiad", author="Homer")
    Book.add(title="The Odyssey", author="Homer")
    Book.add(title="The Aeneid", author="Virgil")


# =======
# EXAMPLE
# =======

with model.query() as select:
    book = Book()
    response = select.distinct(book.author)

# Author names in the results are unique.
print(response.results)
#    author
# 0   Homer
# 1  Virgil


# Without .distinct, select() returns a row for each book, even if multiple books
# have the same author. For instance, the following query returns two rows for
# Homer because there are two books authored by him.

with model.query() as select:
    book = Book()
    response = select(book.author)

print(response.results)
#    author
# 0   Homer
# 1   Homer
# 2  Virgil

See Also#