Skip to content

Using a computed property as a relationship #215

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

Closed
cpa opened this issue Mar 11, 2016 · 4 comments
Closed

Using a computed property as a relationship #215

cpa opened this issue Mar 11, 2016 · 4 comments

Comments

@cpa
Copy link

cpa commented Mar 11, 2016

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!

@jerel
Copy link
Member

jerel commented Mar 15, 2016

@cpa if your function is a property on the model then you don't want SerializerMethodResourceRelatedField as it is analogous to DRF's SerializerMethodField. You likely want ResourceRelatedField.

If this doesn't solve your issue I can reopen.

@jerel jerel closed this as completed Mar 15, 2016
@cpa
Copy link
Author

cpa commented Mar 15, 2016

Thanks for the answer!
Turns out that ResourceRelatedField doesn't work when many=True, which is my use case. See this PR : #151

@jsenecal
Copy link
Member

If you want to work on #151 help yourself :) the original submitter seem to have abandoned the request.

@jerel jerel reopened this Mar 16, 2016
@jerel
Copy link
Member

jerel commented Apr 12, 2016

Fixed by #223

@jerel jerel closed this as completed Apr 12, 2016
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants