Skip to content

Using a computed property as a relationship #215

Closed
@cpa

Description

@cpa

Hello! I'm struggling to include a computed property as a relationship of my model.
I have the following models:

class Language(BaseModel):
    iso_code = models.CharField(max_length=2)

class Sentence(BaseModel):
    body = models.TextField()
    language = models.ForeignKey(Language)

class Dataset(BaseModel):
    name = models.CharField(max_length=100)
    description = models.TextField()
    sentences = models.ManyToManyField(Sentence, blank=True, related_name='datasets', related_query_name='dataset')

Now, I want my Dataset model to have a Language relationship: it should be the list of all (distinct) languages in the sentences of my dataset.

I tried to add:

    @property
    def get_languages(self, obj):
        return TODO

in my Dataset model definition and

    languages = relations.SerializerMethodResourceRelatedField(
        source='get_languages', many=True, model=Language, read_only=True)

in my DataSerializer, but to no avail (getting AttributeError: 'property' object has no attribute 'parent'). What is the correct way to go? Thanks!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions