Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 58 additions & 0 deletions docs/src/development/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -976,6 +976,64 @@ url = "https://development.demo.geonode.org/api/v2/resources/{pk}/linked_resourc
response = requests.request("GET", url)
```

The response groups the links by direction: `linked_to` lists the resources this one points to,
`linked_by` the resources pointing to this one.

```json
{
"linked_to": [
{
"internal": false,
"relation_type": "clone_of",
"pk": 4257,
"title": "Original map",
"resource_type": "map",
"detail_url": "/catalogue/#/map/4257",
"thumbnail_url": null
}
],
"linked_by": []
}
```

Each link carries a `relation_type`, to be read as `<source> <relation_type> <target>`:

| `relation_type` | Meaning | Managed by |
|---|---|---|
| `related` | the source is related to the target | users, from the metadata editor or this API |
| `uses` | the source uses the target (a `Map` and its `Datasets`) | GeoNode, derived from the map layers |
| `clone_of` | the source is a clone of the target | GeoNode, set when a resource is cloned |

The `internal` flag is deprecated, it is `true` only for the `uses` relation. Use `relation_type` instead.

The listing can be filtered with the following query parameters:

- `link_type`: `linked_to` or `linked_by`
- `resource_type`: comma separated list of resource types
- `relation_type`: comma separated list of relation types

2. List the resources cloned from a resource:
```python
import requests

url = "https://development.demo.geonode.org/api/v2/resources/{pk}/linked_resources?link_type=linked_by&relation_type=clone_of"
response = requests.request("GET", url)
```

Links can be created with `POST` and removed with `DELETE` on the same endpoint, passing the list of target ids.
Only `related` links can be created or removed, the other relation types are managed by GeoNode and are rejected
with status code `400`.

```python
import requests

url = "https://development.demo.geonode.org/api/v2/resources/{pk}/linked_resources"
headers = {
'Authorization': 'Basic dXNlcjpwYXNzd29yZA=='
}
response = requests.request("POST", url, headers=headers, json={"target": [4257, 4440]})
```

## Assets

### Get Resource Assets
Expand Down
5 changes: 4 additions & 1 deletion geonode/base/api/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -916,7 +916,10 @@ def __init__(self, *kargs, serialize_source: bool = False, **kwargs):
class Meta:
name = "linked_resources"
model = LinkedResource
fields = ("internal",)
fields = ("internal", "relation_type")

# deprecated, superseded by relation_type
internal = serializers.BooleanField(read_only=True)

def to_representation(self, instance: LinkedResource):
data = super().to_representation(instance)
Expand Down
78 changes: 78 additions & 0 deletions geonode/base/api/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@

from django.urls import reverse
from django.conf import settings
from django.db import IntegrityError, transaction
from django.core.files.uploadedfile import SimpleUploadedFile
from django.contrib.auth import get_user_model

Expand Down Expand Up @@ -4167,6 +4168,83 @@ def test_linked_resource_filter_multiple_resource_type_without_linktype(self):
for d in _d:
d.delete()

def test_linked_resource_relation_type(self):
_d = []
try:
_d.append(LinkedResource.objects.create(source_id=self.map.id, target_id=self.doc.id))
_d.append(
MapLayer.objects.create(
map=self.map,
dataset=self.dataset,
name=self.dataset.name,
current_style="test_style",
ows_url="https://maps.geosolutionsgroup.com/geoserver/wms",
)
)

url = reverse("base-resources-linked_resources", args=[self.map.id])
payload = self.client.get(url).json()
self.assert_linkedres_size(payload, "linked_to", 2)
self.assert_linkedres_contains(
payload,
"linked_to",
(
{"pk": self.doc.id, "relation_type": "related", "internal": False},
{"pk": self.dataset.id, "relation_type": "uses", "internal": True},
),
)

payload = self.client.get(f"{url}?relation_type=uses").json()
self.assert_linkedres_size(payload, "linked_to", 1)
self.assert_linkedres_contains(payload, "linked_to", ({"pk": self.dataset.id, "relation_type": "uses"},))

payload = self.client.get(f"{url}?relation_type=uses,related").json()
self.assert_linkedres_size(payload, "linked_to", 2)

url = reverse("base-resources-linked_resources", args=[self.dataset.id])
payload = self.client.get(f"{url}?relation_type=related").json()
self.assert_linkedres_size(payload, "linked_by", 0)
finally:
for d in _d:
d.delete()

def test_insert_linked_resource_system_relation_type(self):
url = reverse("base-resources-linked_resources", args=[self.doc.id])
self.client.force_login(get_user_model().objects.get(username="admin"))

for relation_type in ("clone_of", "uses", "invalid"):
response = self.client.post(
url, data={"target": [self.map.id], "relation_type": relation_type}, content_type="application/json"
)
self.assertEqual(response.status_code, 400)
self.assertFalse(LinkedResource.objects.filter(source_id=self.doc.id).exists())

response = self.client.post(
url, data={"target": [self.map.id], "relation_type": "related"}, content_type="application/json"
)
self.assertEqual(response.status_code, 200)
self.assertEqual("related", LinkedResource.objects.get(source_id=self.doc.id).relation_type)

def test_delete_linked_resource_keeps_system_relations(self):
url = reverse("base-resources-linked_resources", args=[self.doc.id])
self.client.force_login(get_user_model().objects.get(username="admin"))

clone_of = LinkedResource.objects.create(
source_id=self.doc.id, target_id=self.map.id, relation_type=LinkedResource.RelationType.CLONE_OF
)

response = self.client.delete(url, data={"target": [self.map.id]}, content_type="application/json")
self.assertEqual(response.status_code, 400)
self.assertTrue(LinkedResource.objects.filter(pk=clone_of.pk).exists())

def test_linked_resource_is_unique_per_relation_type(self):
LinkedResource.objects.create(source_id=self.doc.id, target_id=self.map.id)
LinkedResource.objects.create(
source_id=self.doc.id, target_id=self.map.id, relation_type=LinkedResource.RelationType.CLONE_OF
)
with self.assertRaises(IntegrityError), transaction.atomic():
LinkedResource.objects.create(source_id=self.doc.id, target_id=self.map.id)


class TestApiAdditionalBBoxCalculation(GeoNodeBaseTestSupport):
@classmethod
Expand Down
19 changes: 17 additions & 2 deletions geonode/base/api/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -1310,6 +1310,11 @@ def linked_resources(self, request, pk, *args, **kwargs):
if not isinstance(target_ids, list):
raise ValidationError("Payload is not valid")

# the other relation types are managed by the system
relation_type = request.data.get("relation_type", LinkedResource.RelationType.RELATED)
if relation_type != LinkedResource.RelationType.RELATED:
raise ValidationError(f"Relation type '{relation_type}' can not be set")

# remove duplicates and self ref
target_ids = set(target_ids)
if resource.id in target_ids:
Expand All @@ -1330,13 +1335,17 @@ def linked_resources(self, request, pk, *args, **kwargs):
continue

if request.method == "POST":
_, created = LinkedResource.objects.get_or_create(source=resource, target=target)
_, created = LinkedResource.objects.get_or_create(
source=resource, target=target, relation_type=relation_type
)
if created:
success_var.append(t_id)
continue
error_var.append(t_id)
if request.method == "DELETE":
link = LinkedResource.objects.filter(source=resource.id, target=t_id).first()
link = LinkedResource.objects.filter(
source=resource.id, target=t_id, relation_type=relation_type
).first()
if not link:
logger.error(f"Resource selected with id {t_id} does not exist")
error_var.append(t_id)
Expand Down Expand Up @@ -1517,7 +1526,9 @@ def base_linked_resources(instance, user, params):
def base_linked_resources_instances(instance, user, params={}):
resource_type = params.get("resource_type", None)
link_type = params.get("link_type", None)
relation_type = params.get("relation_type", None)
type_list = resource_type.split(",") if resource_type else []
relation_types = relation_type.split(",") if relation_type else []

warnings = {}

Expand Down Expand Up @@ -1545,6 +1556,8 @@ def base_linked_resources_instances(instance, user, params={}):
else:
linked_to_over_loopable = [lr for lr in linked_to_over]
linked_to_id_values = [lr.target_id for lr in linked_to_over_loopable]
if relation_types:
linked_to_over_loopable = [lr for lr in linked_to_over_loopable if lr.relation_type in relation_types]

# filter resources by visibility / permissions
linked_to_visib = get_visible_resources_p(ResourceBase.objects.filter(id__in=linked_to_id_values)).order_by(
Expand All @@ -1565,6 +1578,8 @@ def base_linked_resources_instances(instance, user, params={}):
else:
linked_by_over_loopable = [lr for lr in linked_by_over]
linked_by_id_values = [lr.source_id for lr in linked_by_over_loopable]
if relation_types:
linked_by_over_loopable = [lr for lr in linked_by_over_loopable if lr.relation_type in relation_types]

linked_by_visib = get_visible_resources_p(ResourceBase.objects.filter(id__in=linked_by_id_values)).order_by(
"-pk"
Expand Down
50 changes: 50 additions & 0 deletions geonode/base/migrations/0103_linkedresource_relation_type.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
# Generated by Django 5.2.18 on 2026-11-20 13:49

from django.db import migrations, models
from django.db.models import Count, Min


def migrate_links(apps, schema_editor):
LinkedResource = apps.get_model("base", "LinkedResource")
LinkedResource.objects.filter(internal=True).update(relation_type="uses")

# drop duplicates before the unique constraint is created
duplicates = (
LinkedResource.objects.values("source_id", "target_id", "relation_type")
.annotate(keep=Min("id"), count=Count("id"))
.filter(count__gt=1)
)
for dup in duplicates:
LinkedResource.objects.filter(
source_id=dup["source_id"], target_id=dup["target_id"], relation_type=dup["relation_type"]
).exclude(id=dup["keep"]).delete()


class Migration(migrations.Migration):

dependencies = [
("base", "0102_alter_resourcebase_options"),
]

operations = [
migrations.AddField(
model_name="linkedresource",
name="relation_type",
field=models.CharField(
choices=[("related", "is related to"), ("uses", "uses"), ("clone_of", "is clone of")],
default="related",
max_length=32,
),
),
migrations.RunPython(migrate_links, migrations.RunPython.noop),
migrations.RemoveField(
model_name="linkedresource",
name="internal",
),
migrations.AddConstraint(
model_name="linkedresource",
constraint=models.UniqueConstraint(
fields=("source", "target", "relation_type"), name="unique_linked_resource"
),
),
]
34 changes: 25 additions & 9 deletions geonode/base/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -2001,14 +2001,30 @@ def ows(self):


class LinkedResource(models.Model):
class RelationType(models.TextChoices):
# reads as: <source> <relation_type> <target>
RELATED = "related", _("is related to")
USES = "uses", _("uses")
CLONE_OF = "clone_of", _("is clone of")

source = models.ForeignKey(
ResourceBase, related_name="linked_to", blank=False, null=False, on_delete=models.CASCADE
)
target = models.ForeignKey(ResourceBase, related_name="linked_by", blank=True, null=False, on_delete=models.CASCADE)
internal = models.BooleanField(null=False, default=False)
relation_type = models.CharField(max_length=32, choices=RelationType.choices, default=RelationType.RELATED)

class Meta:
constraints = [
models.UniqueConstraint(fields=["source", "target", "relation_type"], name="unique_linked_resource")
]

@property
def internal(self):
# deprecated, superseded by relation_type
return self.relation_type == self.RelationType.USES

@classmethod
def get_linked_resources(cls, source: ResourceBase = None, target: ResourceBase = None, is_internal: bool = None):
def get_linked_resources(cls, source: ResourceBase = None, target: ResourceBase = None, relation_type: str = None):
if source is None and target is None:
raise ValueError("Both source and target filters missing")

Expand All @@ -2017,20 +2033,20 @@ def get_linked_resources(cls, source: ResourceBase = None, target: ResourceBase
qs = qs.filter(source=source).select_related("target")
if target:
qs = qs.filter(target=target).select_related("source")
if is_internal is not None:
qs = qs.filter(internal=is_internal)
if relation_type is not None:
qs = qs.filter(relation_type=relation_type)
return qs

@classmethod
def get_target_ids(cls, source: ResourceBase, is_internal: bool = None):
def get_target_ids(cls, source: ResourceBase, relation_type: str = None):
sub = LinkedResource.objects.filter(source=source).values_list("target_id", flat=True)
if is_internal is not None:
sub = sub.filter(internal=is_internal)
if relation_type is not None:
sub = sub.filter(relation_type=relation_type)
return sub

@classmethod
def get_targets(cls, source: ResourceBase, is_internal: bool = None):
return ResourceBase.objects.filter(id__in=cls.get_target_ids(source, is_internal))
def get_targets(cls, source: ResourceBase, relation_type: str = None):
return ResourceBase.objects.filter(id__in=cls.get_target_ids(source, relation_type))

@classmethod
def resolve_targets(cls, linked_resources):
Expand Down
5 changes: 4 additions & 1 deletion geonode/layers/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -415,7 +415,10 @@ def get_linked_resources(self, as_target: bool = False):

if as_target:
# create LinkedResources on the fly to report MapLayer relationship
res = (LinkedResource(source=map, target=self, internal=True) for map in self.maps)
res = (
LinkedResource(source=map, target=self, relation_type=LinkedResource.RelationType.USES)
for map in self.maps
)
ret = itertools.chain(ret, res)

return ret
Expand Down
4 changes: 3 additions & 1 deletion geonode/maps/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,9 @@ def get_linked_resources(self, as_target: bool = False):
dataset_ids = MapLayer.objects.filter(map__id=self.id).values("dataset_id")
datasets = ResourceBase.objects.filter(id__in=dataset_ids)
# create LinkedResources on the fly to report MapLayer relationship
res = (LinkedResource(source=self, target=d, internal=True) for d in datasets)
res = (
LinkedResource(source=self, target=d, relation_type=LinkedResource.RelationType.USES) for d in datasets
)
ret = itertools.chain(ret, res)

return ret
Expand Down
Loading
Loading