I'm trying to create a Django application, and I have a class like this in my models.py file:
class Identity(models.Model):
display_name = models.CharField(db_column = "DisplayName", max_length = 200)
When I run python manage.py makemigrations myApp, everything works as expected, and a migration file for the class is created.
The problem happens if the class in the model defines a Meta class as well:
class Identity(models.Model):
display_name = models.CharField(db_column = "DisplayName", max_length = 200)
class Meta:
app_label = "something"
Now, if I run the makemigrations command, I get a "no changes detected" message, and no migration file is generated:
> python manage.py makemigrations myApp
No changes detected in app 'myApp'
Please note that this was just an example, and the problem happens also if I run the command for the first time on a class with a Meta class defined, or if I delete the previously generated migration files.
I'm using Python 2.7.5 and Django 1.9.5 on Windows.
You don't have this in the Meta class do you?
managed = False
Related
I wanted to extend the Base Abstract User Model within Django to have some other Fields:
class Student(AbstractUser):
birth = models.DateField(default=datetime.date.today)
street = models.CharField(max_length=20)
street_number = models.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(99)])
city = models.CharField(max_length=20)
province = models.CharField(max_length=20)
code = models.IntegerField(validators=[MinValueValidator(0, MaxValueValidator(9999))])
address = str(street) + str(street_number) + str(city) + str(code) + str(province)
def __str__(self):
return f'Adresse: {self.address}'
I added this into my settings.py file:
AUTH_USER_MODEL = 'mainApp.Student'
But I get an Error saying there is no such table "Student" when trying to load /admin/.
I have made all the migrations using:
python manage.py makemigrations mainApp
python manage.py migrate mainApp
Error:
OperationalError at /admin/
no such table: mainApp_student
If y'all need any more infos, please comment!
Try in first time to run:
python manage.py makemigrations
python manage.py migrate
Without put the app name to migration process
You cannot define "address" like this. Database column is not for string concatenation of other columns, nor any calculation. It can cause error.
I have a class called Difference in my script "myProject.models.difference.py" that is:
class Difference(models.Model):
comparator = models.ForeignKey(ScenarioComparator, on_delete=models.CASCADE)
summary = models.CharField('summary',max_length=900000)
And in my script "myProject.admin.scenario.py" I have the corresponding admin class:
class DifferenceAdmin(admin.ModelAdmin):
list_display = ("comparator","summary",)
But I need to add two fields more to my Class Difference:
class Difference(models.Model):
comparator = models.ForeignKey(ScenarioComparator, on_delete=models.CASCADE)
summary = models.CharField('summary',max_length=900000)
diff_class = models.CharField('diff_class',max_length=1000)
diff_field = models.CharField('diff_field',max_length=500)
After that I read the next error: "no such column: myproject_difference.diff_class".
But if I comment the new fields diff_class, diff_field of this way:
class Difference(models.Model):
comparator = models.ForeignKey(ScenarioComparator, on_delete=models.CASCADE)
summary = models.CharField('summary',max_length=900000)
#diff_class = models.CharField('diff_class',max_length=1000)
#diff_field = models.CharField('diff_field',max_length=500)
Then the error disappears. ¿What must I do in order to add the new fields?
You need to do a database migration. Save your model:
class Difference(models.Model):
comparator = models.ForeignKey(ScenarioComparator, on_delete=models.CASCADE)
summary = models.CharField('summary',max_length=900000)
diff_class = models.CharField('diff_class',max_length=1000)
diff_field = models.CharField('diff_field',max_length=500)
Then do the following two manage.py commands:
$ python3 manage.py makemigrations
$ python3 manage.py migrate
You will need to do this every time you make changes to models.py
After adding fields to your model, you must make migrations to add the columns to your database
run these two commands
python manage.py makemigrations
python manage.py migrate
In the myProject.models folder, is there an __init__.py file? Inside of it, you'll need this:
from .difference import *
When you have models in a different .py file than models.py, you need to import them in the init.py file, or else the Django app will not know that it's there.
When you did python manage.py makemigrations did it create migrations files in the migrations folder?
The solution is to write a defoult value for diff_class and diff_field. When you run python manage.py makemigrations it appears a warning saying you need defoult values.
So I write
class Difference(models.Model):
comparator = models.ForeignKey(ScenarioComparator, on_delete=models.CASCADE)
summary = models.CharField('summary',max_length=900000)
diff_class = models.CharField('diff_class',max_length=1000,default = 'class')
diff_field = models.CharField('diff_field',max_length=500, default= 'field')
I don't want to use Fake app migrate option for the solution
Please suggest any other method for this problem
Do check my code
Models -
from django.db import models
from mptt.models import MPTTModel, TreeForeignKey
class Delhi(models.Model):
account_id = models.IntegerField()
type_code = models.CharField(max_length=200)
sub_type_code = models.CharField(max_length=200)
name = models.CharField(max_length=200)
credit_amount = models.IntegerField()
debit_amount = models.IntegerField()
# parent = TreeForeignKey('self', null = True, related_name = 'strctr', on_delete = models.CASCADE)
class Meta:
managed = True
db_table = 'gaur'
def __str__(self):
return self.type_code
class Ranchi(MPTTModel):
node_name = models.CharField(max_length = 100)
parent = TreeForeignKey('self', null = True, related_name = 'strctr', on_delete = models.CASCADE)
def __str__(self):
return self.name
Serializer -
from rest_framework import serializers
from .models import Delhi, Ranchi
class DelhiSerializer(serializers.ModelSerializer):
class Meta:
model = Delhi
fields = "__all__"
class RanchiSerializer(serializers.ModelSerializer):
class Meta:
model = Ranchi
fields = "__all__"
View -
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import generics
from rest_framework import status
class CreateView(generics.ListCreateAPIView):
"""This class defines the create behavior of our rest api."""
queryset = Delhi.objects.all()
serializer_class = DelhiSerializer
def perform_create(self, serializer):
"""Save the post data when creating a new bucketlist."""
serializer.save()
class DetailsView(generics.RetrieveUpdateDestroyAPIView):
"""This class handles the http GET, PUT and DELETE requests."""
queryset = Delhi.objects.all()
serializer_class = DelhiSerializer
Database name if hello and table name is 'GAUR' as mention in model.
I tried with same syntax with SQLite configuration, it works for SQLite but when I want to work on database thing it shows the given error on -
python manage.py migrate
error is -
Operations to perform:
Apply all migrations: admin, app1, auth, contenttypes, sessions
Running migrations:
Applying app1.0001_initial...Traceback (most recent call last):
.
.
.
.
.
.
_mysql.connection.query(self, query)
django.db.utils.OperationalError: (1050, "Table 'gaur' already exists")
python manage.py makemigrations
Please suggest a good solution because I have seen all the links of stack for the similar errors, but does give me desired output.
Virtual environment name is - myproject
I tried my making different project under different virtual environment in case the environment is corrupted, but it didnt work.
I even tried on different location with same virtual environment but result was same.
I have encountered this problem, i was scratching my head then i came to know if you simply remove migrations and try again it will work, the problem is when you delete or edit something directly in models.py and try to migrate it will raise this error as already exists, Its not the way to do it,even though you delete or change directly in models.py its not reflected in migrations part, so it will raise error as already exists.
Here is the part taken from.
Remove the all migrations files within your project
Go through each of your projects apps migration folder and remove everything inside, except the init.py file.
Or if you are using a unix-like OS you can run the following script (inside your project dir):
find . -path "*/migrations/*.py" -not -name "__init__.py" -delete
find . -path "*/migrations/*.pyc" -deleteenter code here
that's it.
I just started learning Django yesterday, and I'm having a problem when I trying to add new tables to my MySQL server:
I created a model in models.py (lets say the app name is "article" and the model name is "Article"). I ran syncdb lots of times with different examples in the INSTALLED_APPS in the settings.py (like "article" and "article.models") but it doesn't add the tables.
(Of course I see the other tables like "auth_group", "auth_group_permissions" etc.. but not the table of the Article model I created.)
model.py:
from django.db import models
class Article(models.Model):
title = models.CharField(max_length=200)
body = models.TextField()
pub_date = models.DateTimeField('date publish')
likes = models.IntegerField()
the project structure:
python version: 2.7.9
the db:
The documentation for the new Django migrations is available here:
https://docs.djangoproject.com/en/dev/topics/migrations/
once you have your new app and added it to INSTALLED_APPS in settings.py, you do the following:
python manage.py makemigrations
this will create a python file in the app migrations folder. It will realize the changes, new additions...etc to apply to your database and then you run
python manage.py migrate
no more syncdb, it will be obsolete soon
My django fixture contains the following data:
- model: CkProject.NotificationType
pk: 1
fields:
name: comment
message: commented on your project
When I run python manage.py syncdb, it shows an error while loading the fixtures:
raise base.DeserializationError("Invalid model identifier:
'%s'" % model_identifier)
django.core.serializers.base.DeserializationError: Problem installing fixture
'....../source/apps/CkProject/fixtures/initial_data.yaml':
Invalid model identifier: 'CkProject.NotificationType'
I have even tried with a json file instead of YAML and same error is returned.
UPDATE:
Here is my models.py which is located in apps/Notification/models.py
class NotificationType(models.Model):
class Meta:
db_table = 'CkProject_notificationtype'
name = models.CharField(max_length=50)
message = models.TextField()
def __unicode__(self):
return self.name
You have probably moved your model from apps/CKProject/models.py to apps/Notification/models.py, so its app_label has changed and the model is identified by Django as Notification.NotificationType now. You should update your fixture accordingly.
Alternatively, you can also add app_label = 'CKProject' (see: app_label) to NotificationType's Meta object to make Django identify it as CKProject.NotificationType again.