Skip to content

Why get_value_from_instance in ObjectField returns {} instead of None if related object doesn't exists? #313

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

Open
HardGITer opened this issue Dec 15, 2020 · 1 comment

Comments

@HardGITer
Copy link

Example structure:
Models:

class Author(models.Model):
    name = models.CharField(max_length=30) 

class Article(models.Model):
    name = models.CharField(max_length=100)
    author = models.ForeignKey(Author, on_delete=models.CASCADE)

Documents:

@registries.registry.register_document
class AuthorDocument(Document):
    class Index:
        name = 'author'

    class Django:
        model = models.Author
        fields = ['name']

@registries.registry.register_document
class ArticleDocument(Document):
    author = fields.ObjectField(doc_class=AuthorDocument)

    class Index:
        name = 'article'

    class Django:
        model = models.Article
        fields = ['name']

Create and index article without tags:

art = Article(name="article 1")
art.tag_set  # returns None
# call index logic

For such records we'll get structure to serialize in elasticsearch:

{
    "name": "article 1",
    "tag": {},
}

The main question is why do you return {} instead of None in get_value_from_instance and because of this the field is indexed as {} instead of None?
Django orm returns None in such cases. Maybe better to have similar behavior with Django here? Because difference in concepts breaks some serializer logic: when i use another serializer as serializer field, it tries to serialize related object(when it doesn't exists but elasticsearch returns {}) and i get error because {} doesn't have any fields

@oehrlein
Copy link
Contributor

@HardGITer Can you see if the changes I made here fix your problem: #302

If I'm understanding your issue correctly, then we have/had similar problems.

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

2 participants