Problems adding database columns

Hello, everyone,
I have a problem with a model.

The model was initially created:

class Location(models.Model):
    creator = models.CharField(null=False, max_length = 250)
    slug = models.SlugField(null=True)
    checked = models.BooleanField(null=True)
    lat = models.FloatField(null=True)
    lng = models.FloatField(null=True)
    name = models.CharField(null=True, max_length = 250)
    location_name = models.CharField(null=True, blank=False, max_length = 250)

There are various other models that use “ForeignKey” and “OneToOneField” to create a reference to “Location”.

For example, if I now remove “location_name” and run makemigrations:
remove_location_name… OK

It’s all ok.

However, if I now try to add a new database column (makemigrations), e.g.:

class Location(models.Model):
    creator = models.CharField(null=False, max_length = 250)
    slug = models.SlugField(null=True)
    checked = models.BooleanField(null=True)
    lat = models.FloatField(null=True)
    lng = models.FloatField(null=True)
    name = models.CharField(null=True, max_length = 250)
    follower = models.IntegerField(null=True)

I get this error:

django.db.utils.OperationalError: no such column: app_location.follower

Why is that? For all other models - everything works as desired, even in the same app.

Search your entire code base to see if you’re referencing that field anywhere in your project. Don’t forget to look for references in things like order_by or in filter functions.

Hi Ken,
there are no references to the new field. Even if I:

hsjfwehjbfwe = models.CharField(null=True, max_length = 250)

add to the model and run makemigrationas, this is not accepted, it feels like i can’t add new fields to this model.

Ok, maybe I’m a little confused here. Are you getting this message in the makemigrations command or when you try to run your project after you makemigrations?

(Edit: Also, it may be of value if you posted the complete traceback message you’re getting. Sometimes the “real” error is hidden in the full message.)

In both situations, as soon as I complete the field in the model.

Therefore:

  1. I complete the model (server is not running)
  2. run makemigrations
  3. error “django.db.utils.OperationalError: no such column: app_location.follower”

or:

  1. I complete the model (server is not running)
  2. run runserver
  3. error “django.db.utils.OperationalError: no such column: app_location.follower”

if I remove it from the code again - everything works, just without the new database field.

MacBook-Pro-von-Rene local_fishing % python3 manage.py makemigrations
Traceback (most recent call last):
File “Library/Python/3.8/lib/python/site-packages/django/db/backends/utils.py”, line 84, in _execute
return self.cursor.execute(sql, params)
File “Library/Python/3.8/lib/python/site-packages/django/db/backends/sqlite3/base.py”, line 423, in execute
return Database.Cursor.execute(self, query, params)
sqlite3.OperationalError: no such column: fishing_waters_waters.follower

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File “manage.py”, line 22, in
main()
File “manage.py”, line 18, in main
execute_from_command_line(sys.argv)
File “Library/Python/3.8/lib/python/site-packages/django/core/management/init.py”, line 419, in execute_from_command_line
utility.execute()
File “Library/Python/3.8/lib/python/site-packages/django/core/management/init.py”, line 413, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File “Library/Python/3.8/lib/python/site-packages/django/core/management/base.py”, line 354, in run_from_argv
self.execute(*args, **cmd_options)
File “Library/Python/3.8/lib/python/site-packages/django/core/management/base.py”, line 393, in execute
self.check()
File “Library/Python/3.8/lib/python/site-packages/django/core/management/base.py”, line 419, in check
all_issues = checks.run_checks(
File “Library/Python/3.8/lib/python/site-packages/django/core/checks/registry.py”, line 76, in run_checks
new_errors = check(app_configs=app_configs, databases=databases)
File “Library/Python/3.8/lib/python/site-packages/django/core/checks/urls.py”, line 13, in check_url_config
return check_resolver(resolver)
File “Library/Python/3.8/lib/python/site-packages/django/core/checks/urls.py”, line 23, in check_resolver
return check_method()
File “Library/Python/3.8/lib/python/site-packages/django/urls/resolvers.py”, line 416, in check
for pattern in self.url_patterns:
File “Library/Python/3.8/lib/python/site-packages/django/utils/functional.py”, line 48, in get
res = instance.dict[self.name] = self.func(instance)
File “Library/Python/3.8/lib/python/site-packages/django/urls/resolvers.py”, line 602, in url_patterns
patterns = getattr(self.urlconf_module, “urlpatterns”, self.urlconf_module)
File “Library/Python/3.8/lib/python/site-packages/django/utils/functional.py”, line 48, in get
res = instance.dict[self.name] = self.func(instance)
File “Library/Python/3.8/lib/python/site-packages/django/urls/resolvers.py”, line 595, in urlconf_module
return import_module(self.urlconf_name)
File “/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/importlib/init.py”, line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File “”, line 1014, in _gcd_import
File “”, line 991, in _find_and_load
File “”, line 975, in _find_and_load_unlocked
File “”, line 671, in _load_unlocked
File “”, line 783, in exec_module
File “”, line 219, in _call_with_frames_removed
File “Documents/Projekt Django/local_fishing/local_fishing/urls.py”, line 11, in
path(‘gewaesser/’, include(‘fishing_waters.urls’)),
File “Library/Python/3.8/lib/python/site-packages/django/urls/conf.py”, line 34, in include
urlconf_module = import_module(urlconf_module)
File “/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/importlib/init.py”, line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File “”, line 1014, in _gcd_import
File “”, line 991, in _find_and_load
File “”, line 975, in _find_and_load_unlocked
File “”, line 671, in _load_unlocked
File “”, line 783, in exec_module
File “”, line 219, in _call_with_frames_removed
File “Documents/Projekt Django/local_fishing/fishing_waters/urls.py”, line 2, in
from . import views
File “Documents/Projekt Django/local_fishing/fishing_waters/views.py”, line 148, in
class WaterOverviewView(View):
File “Documents/Projekt Django/local_fishing/fishing_waters/views.py”, line 154, in WaterOverviewView
for entry in Waters.objects.all():
File “Library/Python/3.8/lib/python/site-packages/django/db/models/query.py”, line 280, in iter
self._fetch_all()
File “Library/Python/3.8/lib/python/site-packages/django/db/models/query.py”, line 1324, in _fetch_all
self._result_cache = list(self._iterable_class(self))
File “Library/Python/3.8/lib/python/site-packages/django/db/models/query.py”, line 51, in iter
results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)
File “Library/Python/3.8/lib/python/site-packages/django/db/models/sql/compiler.py”, line 1175, in execute_sql
cursor.execute(sql, params)
File “Library/Python/3.8/lib/python/site-packages/django/db/backends/utils.py”, line 98, in execute
return super().execute(sql, params)
File “Library/Python/3.8/lib/python/site-packages/django/db/backends/utils.py”, line 66, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File “Library/Python/3.8/lib/python/site-packages/django/db/backends/utils.py”, line 75, in _execute_with_wrappers
return executor(sql, params, many, context)
File “Library/Python/3.8/lib/python/site-packages/django/db/backends/utils.py”, line 84, in _execute
return self.cursor.execute(sql, params)
File “Library/Python/3.8/lib/python/site-packages/django/db/utils.py”, line 90, in exit
raise dj_exc_value.with_traceback(traceback) from exc_value
File “Library/Python/3.8/lib/python/site-packages/django/db/backends/utils.py”, line 84, in _execute
return self.cursor.execute(sql, params)
File “Library/Python/3.8/lib/python/site-packages/django/db/backends/sqlite3/base.py”, line 423, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.OperationalError: no such column: fishing_waters_waters.follower

I’d want to take a really good look at your fishing_waters/views.py file. Something is trying to execute model code during initialization.

1 Like

Wow - okay, I didn’t expect that at all.

I identified the error, it’s because of this view:

class WaterOverviewView(View):
    template = "fishing_waters/water-overview.html"
    water_name = []
    for entry in Waters.objects.all():
        water_name.append(entry.water_name)
    context = {
        "water_name": water_name,
    }

    def get(self, request):
        return render(request, self.template, self.context )

Thank you Ken!

Addition - this is a view - yes it was stupid to do it like that :smiley:

Hello, I know this topic has already been solved. But I have the same problem now and I also did something similar in my views.py file: iterating through my_model.objects.all() with a for loop. My question is: why is it a bad idea? :sweat_smile: I am starting with Django and I thought that practice was okay. Can anybody tell me a better way to do this so that I don’t get this error in the future?

Edit: I say it because I simply commented out the piece of code that was causing the error, and then run again python manage.py makemigrations and everything worked as intended. But what if I had a much bigger project? I don’t think it would be a great idea to be commenting everything out every time I need a new field for a model…

Thanks a lot!

This by itself is not a bad idea.

The problem is when you do it in the wrong place (at the module level) instead of in the right place (within a function.)

Solving a specific problem encountered requires seeing the actual error message and the code involved. If you want to get into more specifics, please create a new topic for this conversation.

1 Like

Facing a same problem like when i do it on the wrong place at module level instead of right place then specific problem appeared, Looking for a solution

As I wrote above, solving a specific problem that you are encountering requires seeing the actual error message and the code involved.
If you are having a problem that you would like assistance with, please create a new topic for this conversation. Include the code causing the error in your post.
When posting code, copy/paste the code into the body of your message, between lines of three backtick - ` characters. This means you’ll have a line of ```, then your code, then another line of ```.

heyyy i am getting the same error but dont know how to fixxx . Please Help.
this is my views.py

from django.shortcuts import render,redirect
from .models import Post,BlogComment

Create your views here.

from django.contrib import messages

def blogHome(request):
blogposts = Post.objects.all()
context = {
‘post’: blogposts
}
return render(request, ‘blog/blogHome.html’)
def blogPost(request,slug):
blog = Post.objects.get(slug=slug)
comments = BlogComment.objects.filter(post=blog)
context = {
‘post’: blog, ‘comments’: comments
}
# return HttpResponse(f"This is blogpost where particular blog is rendered {slug} ")
return render(request, ‘blog/blogPost.html’)
def postComment(request):
if request.method ==“POST”:
comment = request.POST.get(‘comment’)
user = request.user
postId = Post.POST.get(‘postId’)
post = Post.objects.get(sno = postId)
comment = BlogComment(comment=comment, user=user,post=post)
comment.save()
messages.warning(request, “your comment has been posted successfully”)
# return HttpResponse(f"This is blogpost where particular blog is rendered {slug} ")
return render(request,‘blog/blogPost.html’)

this is my models.py

from django.db import models
from django.utils.timezone import now
from django.contrib.auth.models import User

class Post(models.Model):
postId = models.AutoField(primary_key=True)

title = models.CharField(max_length=200, unique=True)
slug = models.CharField(max_length=200, unique=True, default="")
category = models.CharField(max_length=200, default="")

author = models.CharField(max_length=10, default="")
updated_on = models.DateTimeField(auto_now= True)
content = models.TextField()
created_on = models.DateTimeField(auto_now_add=True)
thumbnail = models.ImageField(upload_to="images/")


def __str__(self):
    return self.title

class BlogComment(models.Model):
sno = models.AutoField(primary_key=True)
comment = models.TextField()
user = models.ForeignKey(User, on_delete=models.CASCADE)
post = models.ForeignKey(Post, on_delete=models.CASCADE)
parent = models.ForeignKey(‘self’, on_delete=models.CASCADE, null=True)
timestamp = models.DateTimeField(default=now)

this is the error when i added a new field in my model Post (postId)

django.db.utils.OperationalError: no such column: blog_post.postId

Please help me fix it!

This topic has been marked as solved. Your post is going to get more attention if you create a new topic for it.
When posting code, copy/paste the code into the body of your message, between lines of three backtick - ` characters. This means you’ll have a line of ```, then your code, then another line of ```.

If someone is having a similar issue then they can follow the given steps which worked for me :

  1. Identify the respective views and url file from the terminal error . For example in my case the error was something which included
File "/home/mohit/Desktop/Visual Studio Code/LEARN DJANGO/CE/trydjango/urls.py", line 20, in <module>
    from .views import home_view
  File "/home/mohit/Desktop/Visual Studio Code/LEARN DJANGO/CE/trydjango/views.py", line 10, in <module>
    article_obj = Article.objects.get(id=2)

for me it was views.py in trydjango and urls.py where i was trying to execute model during initialization.

  1. To resolve this issue i simply commented out the all the code that required me to use the model that i have made recent changes to .
# """
# To render HTML Pages    
# """
# from django.http  import HttpResponse
# from articles.models import Article
# from django.template.loader  import render_to_string #,get_template


# # getting data from the  sqlite in this form 
# # article_obj = Article.objects.get(id=2)
# # article_list = Article.objects.all()

# # the context to be passed on to the template has to be a dictionary

# myList = [100,200,300,400,500]
# context ={
#     "article_list":article_list,
#     "title": article_obj.title,
#     "content": article_obj.content,
#     "myList":myList
# }

# # Django Templates

# # using get_template 
# # tmpl = get_template('home-view.html')
# # tmpl_string = tmpl.render(context= context)
# # tmpl_string2 = tmpl.render(context= context)

# # using render_to_string
# HTML_STRING = render_to_string('home-view.html', context=context)

# # this way you can access the arguements , parameters passed in the url
# def home_view(request, id=None,*args,**kwargs):
#     print(args,kwargs)
#     print('id : ', id);  
#     return HttpResponse(HTML_STRING)

also in urls.py

 # path("", home_view),  commented the respective home view.

That worked for me . I was stuck at this issue for more than 2 hrs . I wish you don’t have to spend this long on it.

later i realised that even if we comment only the url path that uses this modified Model it seem to work the same way so you can do that only , no need to comment out the views.py .