Search code examples
djangodjongo

Embedded Field: must be instance of Model: <class 'django.db.models.base.Model'>


I tried to do a dummy seeder for the Entry model (extended from djongo model) with the object manager but I got an error while saving.

Error: must be instance of Model: <class 'django.db.models.base.Model'>`

Python script

<The complete python script used to produce the issue.>

from djongo import models
from django.core.management.base import BaseCommand, CommandError

class Blog(models.Model):
    name = models.CharField(max_length=100)
    tagline = models.TextField()

    class Meta:
        abstract = True

class Entry(models.Model):
    _id = models.ObjectIdField()
    blog = models.EmbeddedField(
        model_container=Blog
    )

    headline = models.CharField(max_length=255)
    objects = models.DjongoManager()


def build_dummy_entry():
    e = Entry.objects.create(
    headline='h1',
    blog={
        'name': 'b1',
        'tagline': 't1'
    })

    g = Entry.objects.get(headline='h1')
    assert e == g

    e = Entry()
    e.blog = {
        'name': 'b2',
        'tagline': 't2'
    }
    e.headline = 'h2'
    e.save()


class Command(BaseCommand):
    help='Create a preset dummy entry'

    def handle(self, *args, **options):
        try:
            build_dummy_entry()
            self.stdout.write(self.style.SUCCESS(f'Successfully created dummy blog'))
        except Exception as e:
            raise CommandError(f'{e}')

Traceback
CommandError: Value: {'name': 'b1', 'tagline': 't1'} must be instance of Model: <class 'django.db.models.base.Model'>

---EDIT SOLUTION---

I was using the 1.3.1. I check the version 1.3.2 and 1.3.3 and it looks like these version contains the fix for the instantiation error.


Solution

  • As error says, you should use model instance, but you're using dict.

    def build_dummy_entry():
        e = Entry.objects.create(
            headline='h1',
            blog=Blog(**{'name': 'b2', 'tagline': 't2'}),
        )
    
        ...