question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Allow setting None to NestedModel field

See original GitHub issue

Hi,

I’m setting up my models like this

from fireo import models
class NestedModel(models.Model):
     a = models.TextField()

class TestingTheModel(models.Model):
     nested = models.NestedModel(NestedModel, required=False, default=None)
     b = models.TextField()
     class Meta:
             ignore_none_field = True

and then saving the model:

TestingTheModel(nested=None, b='xd').save()

The Firestore document after this operation:

{
   "nested": {},
   "b": "xd"
}

I would like to get this data in Firestore:

{
   "nested": None,
   "b": "xd"
}

Any tips on how this could be achieved?

I am more than happy to have any solution to his problem: adding parameters, CustomField, extending NestedModel etc. works for me.

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Reactions:2
  • Comments:6 (3 by maintainers)

github_iconTop GitHub Comments

3reactions
montherocommented, Apr 15, 2021

I wrote this “flexible” NestedModelField that has been working quite well for me, allows for repeated nested model as well. Saves things as None, Dict or List[Dict]

class FlexibleNestedModelField(Field):
    allowed_attributes = ["repeated"]
    repeated: bool = False
    required: bool = False

    def __init__(self, model, *args, **kwargs):
        if "required" not in kwargs:
            kwargs["required"] = False

        if 'repeated' not in kwargs:
            kwargs['repeated'] = False

        self.required = kwargs['required']
        super().__init__(*args, **kwargs)
        self.repeated = kwargs['repeated']
        # Check nested model class is subclass for Model
        from fireo.models import Model

        if not issubclass(model, Model):
            raise NestedModelTypeError(
                f'Nested model "{model.__name__}" must be inherit from Model '
                f'class')
        self.nested_model = model

    def attr_repeated(self, attr_val, field_val):
        """Method for attribute auto_add"""
        if attr_val:
            if not field_val:
                return []
            if field_val and not isinstance(field_val, list):
                return [field_val]
        return field_val

    def db_value(self, val):
        if isinstance(val, list) and not self.repeated:
            raise ValueError(
                "Got list but 'repeated' is set to False"
            )

        if val is None and self.required:
            if self.repeated:
                return []
            else:
                raise ValueError(
                    "Value cannot be empty when 'required' is True"
                )

        if val:
            return (
                [entry.to_dict() for entry in val]
                if isinstance(val, list)
                else val.to_dict()
            )

        return val
1reaction
AxeemHaidercommented, Jun 21, 2021

@monthero Thanks for your effort for creating this FlexibleNestedModelField it will be great if you send a PR for this I will merge it. Name it properly instead of FlexibleNestedModelField and if you can write docs for how to use it will be helpful for other.

Fireo Docs

Read more comments on GitHub >

github_iconTop Results From Across the Web

How do i use nested model with none value in pydantic
You have the same model name and field name Emails , this leads to an error. Give a different name for example:
Read more >
Body - Nested Models - FastAPI
With FastAPI, you can define, validate, document, and use arbitrarily deeply nested models (thanks to Pydantic). List fields¶. You can define an attribute...
Read more >
Serializers - Django REST framework - Tom Christie
Serializers allow complex data such as querysets and model instances to be converted to native Python datatypes that can then be easily rendered...
Read more >
Response marshalling - Flask-RESTPlus - Read the Docs
By default when the sub-object is None , an object with default values for the nested fields will be generated instead of null...
Read more >
Nested query | Elasticsearch Guide [8.5] | Elastic
Wraps another query to search nested fields. The nested query searches nested field objects as if they were indexed as separate documents.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found