Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improved error message when attempting to label an unsaved Record such as anArtifact #2372

Open
Zethson opened this issue Jan 23, 2025 · 2 comments
Assignees
Labels

Comments

@Zethson
Copy link
Member

Zethson commented Jan 23, 2025

Add a description

A user ran into:

Traceback (most recent call last):
 File "/fs/gpfs41/lv03/fileset01/pool/pool-mann-maedler-shared/niklas_workspace/lamin_xenium/xenium_to_sdata.py", line 41, in <module>
  art.ulabels.add(technology_xenium)
 File "/fs/home/schmacke/miniforge3/envs/sdata/lib/python3.10/site-packages/django/db/models/fields/related_descriptors.py", line 656, in __get__
  return self.related_manager_cls(instance)
 File "/fs/home/schmacke/miniforge3/envs/sdata/lib/python3.10/site-packages/django/db/models/fields/related_descriptors.py", line 1076, in __init__
  raise ValueError(
ValueError: "Artifact(uid='6sYRmHuqlMUvllcS0000', is_latest=True, description='Ovarian Cancer Xenium Dataset', suffix='.sdata', kind='dataset', size=28462729153, hash='XKMmMiOv9dhZD_v8Q1yp1A', n_files=3403, space_id=1, storage_id=1, run_id=13, created_by_id=5, created_at=<django.db.models.expressions.DatabaseDefault object at 0x14f6481820b0>)" needs to have a value for field "id" before this many-to-many relationship can be used.

and they did not understand this error at all. It's cryptic. We need a better error message that suggest that the Record that is being labeled (an Artifact here but could be anything) needs to be saved first.

@Zethson Zethson self-assigned this Jan 23, 2025
@Zethson Zethson changed the title Improved error message when attempting to label an unsaved Artifact Improved error message when attempting to label an unsaved Record such as anArtifact Jan 23, 2025
@Zethson
Copy link
Member Author

Zethson commented Jan 23, 2025

from django.db.models.fields.related_descriptors import ManyToManyDescriptor
from django.db.models.query import QuerySet

class EnhancedM2MDescriptor(ManyToManyDescriptor):
    def __get__(self, instance, cls=None):
        if instance is not None and not instance.pk:
            raise ValueError(
                f"Cannot access {self.field.name} on unsaved {instance.__class__.__name__}. "
                f"Save {instance.__class__.__name__} first."
            )
        
        manager = super().__get__(instance, cls)
        
        original_bulk_create = manager.bulk_create
        def enhanced_bulk_create(objs, **kwargs):
            if isinstance(objs, (list, QuerySet)):
                unsaved = [obj for obj in objs if not obj.pk]
                if unsaved:
                    raise ValueError(
                        f"Cannot bulk create relationship - these objects need to be saved first: "
                        f"{', '.join(str(obj) for obj in unsaved[:3])}{'...' if len(unsaved) > 3 else ''}"
                    )
            return original_bulk_create(objs, **kwargs)
            
        manager.bulk_create = enhanced_bulk_create
        return manager

class EnhancedManyToManyField(models.ManyToManyField):
    def contribute_to_class(self, cls, name):
        super().contribute_to_class(cls, name)
        setattr(cls, name, EnhancedM2MDescriptor(self.remote_field, self.remote_field.get_related_field()))

A claude starting point for me to reason when I revisit this issue later. This is the complex version with bulk support. I need to look at it properly

@Zethson
Copy link
Member Author

Zethson commented Jan 28, 2025

A user also recently tried things like:

reference = ln.Reference(bla)

artifact.references.add(reference)
artifact.save()

which errored because the Reference was not saved. We need user friendly errors here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant