Iam working on a django project and I am configuring preconfigured database in sqlite3 to postgress locally .First i have done all my migrations to sqlite3 database all was working fine ..
After that i want to migrate to postgressql so i created a local database and connected to it ...
The model iam migrating is ::
class State(models.Model):
statename = models.CharField(db_column='statename',max_length=26,unique=True)
def __str__(self):
return self.statename
class College(models.Model):
statename= models.ForeignKey(State,db_column='statename',on_delete=models.CASCADE,to_field='statename')#used to_field to convert int to text must set unique to true for operation
collegename = models.CharField(db_column='collegename',max_length=30,unique=True)
def __str__(self):
return self.collegename
This are the two databases DDL generated by Django ::
sqlite3 working fine -----
CREATE TABLE api_state
(
id integer PRIMARY KEY AUTOINCREMENT NOT NULL,
statename varchar(25) NOT NULL
);
CREATE UNIQUE INDEX sqlite_autoindex_api_state_1 ON api_state
(statename);
CREATE TABLE api_college
(
id integer PRIMARY KEY AUTOINCREMENT NOT NULL,
collegename varchar(30) NOT NULL,
state varchar(25) NOT NULL,
FOREIGN KEY (state) REFERENCES api_state (statename)
);
CREATE UNIQUE INDEX sqlite_autoindex_api_college_1 ON api_college (collegename);
CREATE INDEX api_college_9ed39e2e ON api_college (state)
postgress ddl changed after generation with Django::
create table api_college
(
id serial not null
constraint api_college_pkey
primary key,
collegename varchar(30) not null,
statename_id integer not null
)
;
create index api_college_b291eb83
on api_college (statename_id)
;
create table api_state
(
id serial not null
constraint api_state_pkey
primary key,
statename varchar(25) not null
)
;
alter table api_college
add constraint api_college_statename_id_7e126c2d_fk_api_state_id
foreign key (statename_id) references api_state
deferrable initially deferred
;
Error that iam getting int he postgress migration ::
File "/home/hexnor/apienv/lib/python3.5/site-packages/django/utils/six.py", line 685, in reraise
raise value.with_traceback(tb)
File "/home/hexnor/apienv/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
django.db.utils.DataError: value too long for type character varying(3)
Error that i got after confguring postgress database and access django admin on browser::
i have first added state UP
then when iam choosing state as Up and adding college as testcollege iam getting this error ::
Exception Type: ProgrammingError
Exception Value:
column "statename" of relation "api_college" does not exist
LINE 1: INSERT INTO "api_college" ("statename", "collegename") VALUE...
Related
I'm creating a web app with Clojure and Luminus, but when I create a migration file with all the tables I need, it will only create the first. This is my user-table.up.sql file:
CREATE TABLE UserTable (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name VARCHAR(50),
last_name VARCHAR(50),
gender VARCHAR(50),
email VARCHAR(50) UNIQUE,
password VARCHAR(400),
time_stamp TIMESTAMP,
is_active BOOLEAN
);
CREATE TABLE LoginTable (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER,
time_stamp TIMESTAMP
);
When I run lein run migrate, only the table UserTable is created. Is this supposed to work like this? Do I need to create a migration file for each table?
As you are using Luminus, you are probably using Migratus. If you want to execute multiple statements in one sql file, read this:
https://github.com/yogthos/migratus#multiple-statements
Just to let Michiel answer here according your case, to run multiple statements in your migration, separate them with --;; in your case:
CREATE TABLE UserTable (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name VARCHAR(50),
last_name VARCHAR(50),
gender VARCHAR(50),
email VARCHAR(50) UNIQUE,
password VARCHAR(400),
time_stamp TIMESTAMP,
is_active BOOLEAN
);
--;;
CREATE TABLE LoginTable (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER,
time_stamp TIMESTAMP
);
My models:
class TestSkill(models.Model):
name = models.CharField(max_length=255)
value = models.CharField(max_length=255)
class Girl(models.Model):
skills = models.ManyToManyField(TestSkill)
this has created following sql statement:
CREATE TABLE "my_app_girl_skills" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "girl_id" integer NOT NULL REFERENCES "my_app_girl" ("id"), "testskill_id" integer NOT NULL REFERENCES "my_app_testskill" ("id"))
And after I tried manually to create a row in db using sql lite browser I 've got an error:
Foreign constraint failed
I am making a Django App and having the following issue when I am trying to add something to the table 'device' of my app from the admin interface:
column device.plID_id does not exist
Here is class:
class Device(models.Model):
id = models.IntegerField(primary_key=True)
name = models.CharField(max_length = 20)
slug = models.SlugField(unique=True,help_text='URL page created from name')
model_name = models.CharField(max_length = 20)
plID = models.ForeignKey('onep_web.Platform', unique = False)
sdkID = models.ForeignKey('onep_web.SDKVersion',unique = False)
IPID = models.ForeignKey('onep_web.IPAddress',unique = False)
and output of sqall command:
BEGIN;
CREATE TABLE "device" (
"id" integer NOT NULL PRIMARY KEY,
"name" varchar(20) NOT NULL,
"slug" varchar(50) NOT NULL UNIQUE,
"model_name" varchar(20) NOT NULL,
"plID_id" integer NOT NULL,
"sdkID_id" integer NOT NULL,
"IPID_id" integer NOT NULL
)
;
CREATE TABLE "platform" (
"id" integer NOT NULL PRIMARY KEY,
"platform_name" varchar(20) NOT NULL
)
;
ALTER TABLE "device" ADD CONSTRAINT "plID_id_refs_id_364a8522" FOREIGN KEY ("plID_id") REFERENCES "platform" ("id") DEFERRABLE INITIALLY DEFERRED;
CREATE TABLE "sdk_ver" (
"id" integer NOT NULL PRIMARY KEY,
"language" varchar(20) NOT NULL,
"version" numeric(100, 100) NOT NULL
)
;
ALTER TABLE "device" ADD CONSTRAINT "sdkID_id_refs_id_bb71f431" FOREIGN KEY ("sdkID_id") REFERENCES "sdk_ver" ("id") DEFERRABLE INITIALLY DEFERRED;
CREATE TABLE "ip_addr" (
"id" integer NOT NULL PRIMARY KEY,
"ip" inet NOT NULL
)
;
ALTER TABLE "device" ADD CONSTRAINT "IPID_id_refs_id_7c42b845" FOREIGN KEY ("IPID_id") REFERENCES "ip_addr" ("id") DEFERRABLE INITIALLY DEFERRED;
CREATE TABLE "files" (
"id" integer NOT NULL PRIMARY KEY,
"file" varchar(100) NOT NULL,
"isConfig" boolean NOT NULL
)
;
CREATE INDEX "device_slug_like" ON "device" ("slug" varchar_pattern_ops);
CREATE INDEX "device_plID_id" ON "device" ("plID_id");
CREATE INDEX "device_sdkID_id" ON "device" ("sdkID_id");
CREATE INDEX "device_IPID_id" ON "device" ("IPID_id");
When there were only two tables Device and Platform everything was OK. After I added a few more tables I have this issue
Django's manage.py, does not use or handles migrations (currently) you need to use south to alter tables (when you alter models):
http://south.aeracode.org/
Install south, follow the detailed instructions and you will easily maintain your schema up to date.
Question> Why django 1.3 ('ENGINE': 'django.db.backends.sqlite3' ) doesn't apply constraint on the tag_id attribute of table bookmarks_tag_bookmark?
Generated:
CREATE TABLE "bookmarks_tag_bookmarks" (
"id" integer NOT NULL PRIMARY KEY,
"tag_id" integer NOT NULL,
"bookmark_id" integer NOT NULL REFERENCES "bookmarks_bookmark" ("id"),
UNIQUE ("tag_id", "bookmark_id")
)
;
Expected:
CREATE TABLE "bookmarks_tag_bookmarks" (
"id" integer NOT NULL PRIMARY KEY,
"tag_id" integer NOT NULL REFERENCES "bookmarks_tag" ("id"),
"bookmark_id" integer NOT NULL REFERENCES "bookmarks_bookmark" ("id"),
UNIQUE ("tag_id", "bookmark_id")
)
;
# ----- Detail of The Coding ------------ #
user#ubuntu:~/Documents/Django/django_bookmarks$ cat bookmarks/models.py
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Link(models.Model):
url = models.URLField(unique=True)
class Bookmark(models.Model):
title = models.CharField(max_length=200)
user = models.ForeignKey(User)
link = models.ForeignKey(Link)
class Tag(models.Model):
name = models.CharField(max_length=64, unique=True)
bookmarks = models.ManyToManyField(Bookmark)
user#ubuntu:~/Documents/Django/django_bookmarks$ python manage.py syncdb
user#ubuntu:~/Documents/Django/django_bookmarks$ python manage.py sql bookmarks
BEGIN;
CREATE TABLE "bookmarks_link" (
"id" integer NOT NULL PRIMARY KEY,
"url" varchar(200) NOT NULL UNIQUE
)
;
CREATE TABLE "bookmarks_bookmark" (
"id" integer NOT NULL PRIMARY KEY,
"title" varchar(200) NOT NULL,
"user_id" integer NOT NULL REFERENCES "auth_user" ("id"),
"link_id" integer NOT NULL REFERENCES "bookmarks_link" ("id")
)
;
CREATE TABLE "bookmarks_tag_bookmarks" (
"id" integer NOT NULL PRIMARY KEY,
"tag_id" integer NOT NULL,
"bookmark_id" integer NOT NULL REFERENCES "bookmarks_bookmark" ("id"),
UNIQUE ("tag_id", "bookmark_id")
)
;
CREATE TABLE "bookmarks_tag" (
"id" integer NOT NULL PRIMARY KEY,
"name" varchar(64) NOT NULL UNIQUE
)
;
COMMIT;
user#ubuntu:~/Documents/Django/django_bookmarks$
Because bookmarks_tag is not created at that point, so it can't define the constraint at table creation time. However if you do manage.py sqlall you will see that it later does an ALTER TABLE to add the constraint once all the tables are created.
(Although it's worth pointing out that Sqlite ignores contraints except in very recent versions, and even then only if specifically enabled.)
Django 1.3
Python 2.7
In fixing one error, I've developed another. I'm not even sure where to begin, I'm so frustrated.
I got my app to show up in the Django admin section, and when I click on "add", it brings up the form. When I fill it out & submit it, it results in this error:
Exception Value: (1048, "Column 'user_id' cannot be null")
Seems simple & clear, but if I add user_id to my admin.py, then it results in the error I just fixed. If I leave it out and use the code that fixes the old error, then I get this error. Here's the relevant code:
admin.py (I commented out the code I was using, as that caused the earlier error)
from timeslip.models import Timeslip
from django.contrib import admin
class TimeslipAdmin(admin.ModelAdmin):
pass
#fields = ['user_id','day','hours_as_sec','part_of_day','drove','gas_money','notes']
admin.site.register(Timeslip, TimeslipAdmin)
models.py
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Timeslip(models.Model):
user=models.ManyToManyField(User)
day = models.DateField()
hours_as_sec = models.PositiveIntegerField()
part_of_day = models.CharField(max_length=16,choices=PART_O_DAY)
drove = models.BooleanField(default=False)
gas_money = models.DecimalField(max_digits=5,decimal_places=2)
notes = models.TextField()
class UserProfile(models.Model):
user = models.ForeignKey(User)
url = models.URLField("Website", blank=True)
position = models.CharField(max_length=50, blank=True)
User.profile = property(lambda u: UserProfile.objects.get_or_create(user=u)[0])
If I make Timeslip's user=, into a ForeignKey(User) instead of a ManyToManyField(User), the error becomes:
Exception Value: (1062, "Duplicate entry '2' for key 'user_id'")
...which I understand, but that's exactly what I'm trying to do here now -- make multiple timeslips for each user.
How do I do that? I keep getting ridiculous errors no matter what I try, and it's hard finding documentation on this even though it seems like it would be a common & basic thing.
Update:
New question. Is Django caching stuff? I removed something from the model and reset everything but it still shows the old form. If it's showing me something it cached - How do I flush that cache?
Anyway, here's the output when I run manage.py sqlall timeslip
BEGIN;
CREATE TABLE `timeslip_timeslip` (
`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY,
`user_id` integer NOT NULL,
`day` date NOT NULL,
`hours_as_sec` integer UNSIGNED NOT NULL,
`part_of_day` varchar(16) NOT NULL,
`drove` bool NOT NULL,
`gas_money` numeric(5, 2) NOT NULL,
`notes` longtext NOT NULL
)
;
ALTER TABLE `timeslip_timeslip` ADD CONSTRAINT `user_id_refs_id_bb29929c` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`);
CREATE TABLE `timeslip_userprofile_user` (
`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY,
`userprofile_id` integer NOT NULL,
`user_id` integer NOT NULL,
UNIQUE (`userprofile_id`, `user_id`)
)
;
ALTER TABLE `timeslip_userprofile_user` ADD CONSTRAINT `user_id_refs_id_c73880a3` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`);
CREATE TABLE `timeslip_userprofile` (
`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY,
`url` varchar(200) NOT NULL,
`company` varchar(50) NOT NULL
)
;
ALTER TABLE `timeslip_userprofile_user` ADD CONSTRAINT `userprofile_id_refs_id_d05b8c80` FOREIGN KEY (`userprofile_id`) REFERENCES `timeslip_userprofile` (`id`);
CREATE INDEX `timeslip_timeslip_fbfc09f1` ON `timeslip_timeslip` (`user_id`);
COMMIT;