django-mongoengine icon indicating copy to clipboard operation
django-mongoengine copied to clipboard

something wrong with django_mongoengine/forms/document_options.py

Open BradyHu opened this issue 4 years ago • 4 comments

If the name of the reference field is different from the name of the reference, it will cause a KeyError.

    def get_field_by_name(self, name):
        """
        docs
        """
        try:
            try:
                return self._field_cache[name]
            except TypeError:
                self._init_field_cache()
                return self._field_cache[name]
        except KeyError:
            raise FieldDoesNotExist('%s has no field named %r'
                                    % (self.object_name, name))
    def _init_field_cache(self):
        if self._field_cache is None:
            self._field_cache = {}

        for f in self.document._fields.values():
            if isinstance(f, ReferenceField):
                document = f.document_type
                self._field_cache[document._meta.module_name] = (f, document, False, False)
            else:
                self._field_cache[f.name] = (f, None, True, False)

        return self._field_cache

BradyHu avatar Jun 24 '21 02:06 BradyHu

change self._field_cache[document._meta.module_name] to self._field_cache[f.name] maybe will work,I guess

BradyHu avatar Jun 24 '21 02:06 BradyHu

Hi.

Would you try to fix this issue?

You need to add test case exposing issue, and then try your fix and create PR.

last-partizan avatar Jun 26 '21 08:06 last-partizan

I know when it happened now: when I use DRF and serializers.PrimaryKeyFIeld, It happened, while ,I dont know how to fix it....

class SceneBIReport(MongoCoreModel):
    stats_field = fields.ReferenceField(DataField, reverse_delete_rule=mongoengine.NULLIFY,
                                        blank=True, null=True)

class SceneBIReportSerializer(m_serializers.DocumentSerializer):
    stats_field = serializers.PrimaryKeyRelatedField(
        queryset=models.DataField.objects.all(),
        required=False,
        allow_null=True,
        allow_empty=True,
    )

and when run validate , problem happened....

BradyHu avatar Jun 30 '21 05:06 BradyHu

You suggested changing something in _init_field_cache, so you could start to creating test case for this issue.

DRF is probably unrelated, take a look at validation, find out what is being called. Then create test for it and reproduce bug.

Then, try your suggestion:

change self._field_cache[document._meta.module_name] to self._field_cache[f.name] maybe will work,I guess

If it works, create PR.

last-partizan avatar Jun 30 '21 17:06 last-partizan