Skip the __init__ argument of the object model class in the iteration query set

I have a model with an overridden method __init__as follows:

class MyModel(models.Model):
    ...

    def __init__(self, *args, **kwargs):
        if not kwargs.get('skip', False):
            do_something()
        super().__init__(*args, **kwargs) 

How to pass an argument skipto __init__when I repeat the request:

data = [obj for obj in MyModel.objects.all()]

I would like to implement this using a method in the user manager, to use it something like this: queryset.with_skip()

+4
source share
1 answer

I see that you are not removing the argument skipfrom kwargsbefore passing it to super().__init__. This means that "skip" is the name of the field, otherwise you get an exception TypeError("'skip' is an invalid keyword argument for this function").

do_something(), , , (??), .. .

, models.Model.__init__(...) *args **kwargs , . , "" , . , . :

... , __init__() . cls(*values)...
.
| @classmethod
| def from_db(cls, db, field_names, values):
| ...
| instance = cls(*values)
| ...

- do_something() super().__init__ self.skip kwargs, args.

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs) 
        if not self.skip:
            do_something()

"post_init", super().__init__, .

*args (, - ):

    def __init__(self, *args, **kwargs):
        if kwargs:
            skip = kwargs.get('skip', False)
        else:
            # check "val is True" in order to skip if val is DEFERRED
            skip = any(field.name == 'skip' and val is True
                       for val, field in zip(args, self._meta.concrete_fields)
                       )
        if not skip:
            do_something()
        super().__init__(*args, **kwargs)

EDIT: , , , -, - - . ( "" , , , . , .)

+2

Source: https://habr.com/ru/post/1684874/


All Articles