mayhemds
mayhemds

Reputation: 434

Django model.foreignKey and return self.text errors

So I'm working on the model.py in Django and i'm getting 2 pylint errors. I don't understand why? is this an issue with pylint or something i'm doing wrong in my code.

E1120:No value for argument 'on_delete' in constructor call    
E1136:Value 'self.text' is unsubscriptable

If I remove the entry class the code works

from django.db import models

# Create your models here.
class Topic(models.Model):
"""A topic the user is learning about"""
text = models.CharField(max_length=200)
date_added = models.DateTimeField(auto_now_add=True)

def __str__(self):
    """Return a string representation of the model."""
    return self.text

class Entry(models.Model):
"""Something specific learned about a topic"""
topic = models.ForeignKey(Topic)
text = models.TextField()
date_added = models.DateTimeField(auto_now_add=True)

class Meta:
    verbose_name_plural = "entries"

def __str__(self):
    """Return a string representation of the model."""
    return self.text[:50] + "..."

Upvotes: 3

Views: 4246

Answers (3)

user10678889
user10678889

Reputation:

To prevent this, we should use on_delete=models.PROTECT.

By default Django uses on_delete=models.CASCADE but this is not secure if object deleted accidentally.

In that case there would be no notification of deleted objects so it would be ideal to use models.PROTECT.

Upvotes: 0

Gavin.Hall
Gavin.Hall

Reputation: 1

The reason of second issue is you missed the command after the command python manage.py makemigrations [appname], the missing command is python manage.py migrate.

Upvotes: 0

mayhemds
mayhemds

Reputation: 434

The problem was ForeignKey in Django 1.9 required 1 positional argument in Django 2.0 ForeignKey 2 required positional argument

  topic = models.ForeignKey("Topic", on_delete=models.PROTECT)

Upvotes: 7

Related Questions