Property.has_many()#

relationalai
#Property.has_many() -> None

Declare a multi-valued property.

Example#

Use .has_many() to declare a multi-valued property:

#import relationalai as rai

# Create a model named "PetsModel" with Person and Pet types.
model = rai.Model("PetsModel")
Person = model.Type("Person")
Pet = model.Type("Pet")

# Declare the Person.pets property to be multi-valued. NOTE: This is optional.
Person.pets.has_many()

# Check that the Person.pets property is multi-valued.
print(Person.pets.is_multi_valued)
# True

# Define Person and Pet objects.
with model.rule():
    alice = Person.add(name="Alice")
    # Note that alice.pets.add() automatically creates a multi-valued pets property
    # if the .has_many() declaration is missing.
    alice.pets.add(Pet.add(name="Fluffy", type="cat"))

    bob = Person.add(name="Bob")
    # Like .add(), bob.pets.extend() creates a multi-valued pets property if the
    # .has_many() declaration is missing.
    bob.pets.extend([
        Pet.add(name="Spot", type="dog"),
        Pet.add(name="Rex", type="dog")
    ])

.has_many() is optional in most cases. Calling InstanceProperty.add() or InstanceProperty.extend() automatically creates a multi-valued property if it hasn’t been declared.

The one case where .has_many() is required is when defining a Type from a Snowflake table. By default, properties of objects created from rows in a Snowflake table are single-valued. If you intend to use one of the properties as multi-valued — for example, by adding more values to the property in your model’s rules — you must declare it with .has_many():

#import relationalai as rai

model = rai.Model("students")

# Declare a Student type with objects created from the students tables in the
# sandbox.public Snowflake schema.
Student = model.Type("Student", source="sandbox.public.students")

# Declare the email property of the Student type to be multi-valued.
Student.email.has_many()

See Also#