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

support skipping disabled related fields #2

Open
gbezyuk opened this issue Oct 13, 2017 · 2 comments
Open

support skipping disabled related fields #2

gbezyuk opened this issue Oct 13, 2017 · 2 comments

Comments

@gbezyuk
Copy link
Owner

gbezyuk commented Oct 13, 2017

Let's say you have a model named Gallery, having One-to-Many relation to the second model, GalleryPhoto. Also, let's say GalleryPhoto has a boolean is_enabled field.

class Gallery(models.Model, ToDictMixin):
    pass

class GalleryPhoto(models.Model, ToDictMixin):
    gallery = models.ForeignKey(to=Gallery, related_name='photos')
    is_enabled = models.BooleanField(default=True, verbose_name=_('is enabled'))

There should be a way to skip photos with is_enabled=False.

@gbezyuk
Copy link
Owner Author

gbezyuk commented Oct 13, 2017

Current workaround for solving this issue is adding custom _to_dict_related_fields_strategy to the parent model:

class Gallery(models.Model, ToDictMixin):
    def _to_dict_related_fields_strategy(self, result):
        related_fields = [rf for rf in self._meta.get_fields() if rf.is_relation]
        for rf in related_fields:
            # TODO recursion using __ive_been_there_already to prevent stack overflow
            if rf.one_to_many:
                if not rf.related_name:
                    continue
                result[rf.related_name] = [
                    i.to_dict(inspect_related_objects=False) for i in getattr(self, rf.related_name).filter(is_enabled=True)]
            if rf.many_to_one or rf.one_to_one:
                related_object = getattr(self, rf.name)
                if hasattr(related_object, 'to_dict'):
                    result[rf.name] = related_object.to_dict(inspect_related_objects=False)
            if rf.many_to_many:
                print('many_to_many', rf.name, rf)

See filter(is_enabled=True) in the snippet.

@gbezyuk
Copy link
Owner Author

gbezyuk commented Oct 29, 2017

print('many_to_many', rf.name, rf) TODO remove =)

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

1 participant