0

Using

  • Django: 1.11
  • Python 3.6
  • DRF: 3.7
  • DREST (aka dynamic rest): 1.8

I have a serializer written like this:

class SubProjectAsFKWithAttachedFieldsSerializer(DynamicModelSerializer):
    # attached_fields = AttachedFieldSerializer(embed=True, many=True)
    try:
        scope_object = UgField.objects.get(dotted_path='global.scope')
        scopes = DynamicRelationField(
            AttachedFieldWithDirectValuesSerializer,
            source='attached_fields',
            many=True,
            embed=True,
            read_only=True,
            queryset=AttachedField.objects.filter(ug_field=scope_object)
        )
    except ObjectDoesNotExist:
        scopes = DynamicRelationField(AttachedFieldWithDirectValuesSerializer,
                                      source='attached_fields',
                                      many=True,
                                      read_only=True,
                                      embed=True)

Currently, in almost all my tests.py in the setUp method, I have

self.global_scope_field = UgFieldFactory(dotted_path='global.scope', name='Scope')

For some reason, this line

scope_object = UgField.objects.get(dotted_path='global.scope')

keeps failing despite that I have "instantiated" using a DjangoModelFactory

What should I do to ensure that line always passes when I run tests?

UPDATE

  1. Just to point out I actually have a UgField record which has the string global.scope as the value for the field dotted_path.
  2. Only when I run python manage.py test do I face this issue.
  3. When I run the app proper, there's no issue.

I have also tried setting

(self.global_scope_field, created) = UgField.objects.get_or_create(dotted_path='global.scope', name='Scope')

in my setUp method.

but then I get the same issue

enter image description here

Kim Stacks
  • 10,202
  • 35
  • 151
  • 282
  • erm I actually have a UgField record which has the string `global.scope` as the value for the field `dotted_path`. When I run the app proper, there's no issue. Only during tests do I face this issue – Kim Stacks Nov 13 '18 at 09:03
  • Maybe at the time of testing the record doesn't exist, but during runtime it already exists so you get a different serializer? Perhaps initialize it at a different point in the test framework? Using `try` in a class is just... sketchy, though clever. I hope the reporting it does is accurate in that case, i've no experience. Perhaps its actually throwin an exception on the code in the except: field – Andrew Nov 22 '18 at 08:42

1 Answers1

0

For an object to be retrievable with .get() it has to be saved.

self.global_scope_field = UgFieldFactory(dotted_path='global.scope', name='Scope')
self.global_scope_field.is_valid()
self.global_scope_field.save()

Alternatively you could just create the object without a form.

self.global_scope_field = UgField.objects.create(dotted_path='global.scope', name='Scope')
bdoubleu
  • 5,568
  • 2
  • 20
  • 53