# Create the relationshipagent.customize_collection("order").add_many_to_one_relation("delivery_address", "Address", "delivery_address_id")# Create the reverse relationshipagent.customize_collection("Address").add_one_to_many_relation("orders", "Order", "delivery_address_id")
Relationships when you need complex logic to get a foreign key
In this example, we want to create a relationship between the order collection and the address collection (assuming that it does not already exist in the database because depends on complex logic).
We can see that in the legacy agent, the delivery_address field was a smart field that returned the full address of the order, while in the new agent, we will create a computed field that will contain the address ID (the foreign key), and then create the relationship.
We won't be detailing the migration of a relation to a list of records here, but it is very similar to the one described below.
If the foreign key was already present in the database in a related table, use the import-rename-delete feature to move it to the correct collection instead of using a computed field.
This will be much faster and will not require In filter operators to be implemented (as unlike computed fields, imported fields are natively filterable and sortable).
from app.models import Addressfrom django_forest.utils.collection import Collection# Many to one relationshipsclassOrderForest(Collection):defload(self): self.fields = [{"field":"delivery_address","type":"String","reference":"Address.id","get": self.get_delivery_address,} ]defget_delivery_address(self,obj):return Address.objects.filter( """complex_query""" )
from typing import List, Dictfrom app.models import Addressfrom forestadmin.datasource_toolkit.context.collection_context import CollectionCustomizationContextfrom forestadmin.datasource_toolkit.interfaces.records import RecordsDataAliasdefget_delivery_address_id(records: List[RecordsDataAlias],context: CollectionCustomizationContext): addresses_by_order_id = Address.objects.filter("""complex_query_here""")return [addresses_by_order_id[order["id"]]["id"] for order in records]# Create a computed field that will contain the address ID (the foreign key)agent.customize_collection("order").add_field("delivery_address_id", {"column_type": "Number","dependencies": ["id"],"get_values": get_delivery_address_id}).replace_field_operator(# Make the field filterable (this is required for the relationship to work)"delivery_address_id", "in",lambdavalue, context: pass# implement the reverse-lookup logic here).add_many_to_one_relation(# Create the relationship"delivery_address", "Address", "delivery_address_id")