Search code examples
pythondjangoforeign-keys

Cannot assign “1”: “Plugins.category” must be a “PluginsCategory” instance. Django and ForeignKey


I am trying to save a new record to the database, and an error occurred while writing to the ForeignKey

Cannot assign "1": "Plugins.category" must be a "PluginsCategory" instance.

What's wrong?

models.py

class Plugins(models.Model):
    title = models.CharField(max_length=150, verbose_name='Название')
    category = models.ForeignKey('PluginsCategory', on_delete=models.PROTECT, related_name='get_category')

    def get_absolute_url(self):
        return reverse('urls_view_current_plugins', kwargs={'pk': self.pk})

    def __str__(self):
        return self.title


class PluginsCategory(models.Model):
    title = models.CharField(max_length=150, db_index=True, verbose_name='Наименования категории')

    def __str__(self):
        return self.title

tags.py

def add_plugin_in_db():
    plugin = Plugins()
    plugin.title = 'title'
    plugin.category = 1
    plugin.save(force_insert=True)

On the site

C:\PythonProject\ServiceCRM3\venv\lib\site-packages\django\db\models\fields\related_descriptors.py, line 215, in __set__
            raise ValueError( …
▼ Local vars
Variable    Value
instance    
<Plugins: Заказы>
self    
<django.db.models.fields.related_descriptors.ForwardManyToOneDescriptor object at 0x000000000438DAF0>
value   
1

Solution

  • You assign this with the category_id field, so:

    ef add_plugin_in_db():
        plugin = Plugins()
        plugin.title = 'title'
        plugin.category_id = 1
        plugin.save(force_insert=True)

    You can however make this more compact to:

    def add_plugin_in_db():
        plugin = Plugins.objects.create(
            title = 'title'
            category_id=1
        )