FOREIGN KEY MULTI FIELD HELP! - foreign-keys

I have 2 table
TABLE CLASS
(
school varchar(50),
year varchar(50),
grade varchar(50),
className varchar(50),
PRIMARY KEY (school,year,grade,className)
)
TABLE STUDENT
(
student_id varchar(50) PRIMARY KEY,
detail varchar(50)
)
Now, I want to subclass for students. How to create a reference?

Just do what everyone else does...
CREATE TABLE CLASS (
id int not null auto_increment PRIMARY KEY, -- CREATE A KEY COLUMN
school varchar(50),
year varchar(50),
grade varchar(50),
className varchar(50),
unique (school,year,grade,className)
);
CREATE TABLE STUDENT (
student_id varchar(50) PRIMARY KEY,
class_id int references class, -- REFERENCE THE KEY
detail varchar(50)
);

Related

Clojure Luminus Migrations - Only one table per migration file

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
);

Column doesn't exist

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.

In Django, is the primary_key option ignored when a model is part of a Many to Many relationship?

I have two models:
class StateTax(models.Model):
name = models.CharField(max_length=256)
abbr = models.CharField(max_length=64, primary_key=True)
rate = models.IntegerField(default=0)
class Account(models.Model):
name = models.CharField(max_length=32)
tax_regions = models.ManyToManyField(SalesTaxRegion, blank=True, null=True, related_name="accounts")
However the SQL Django creates during syncdb seems to ignore the primary_key option. For example:
CREATE TABLE `airship_salestaxregion` (
`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY,
`name` varchar(256) NOT NULL,
`abbr` varchar(64) NOT NULL,
`rate` integer NOT NULL
)
;
CREATE TABLE `airship_account_tax_regions` (
`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY,
`account_id` integer NOT NULL,
`salestaxregion_id` integer NOT NULL,
UNIQUE (`account_id`, `salestaxregion_id`)
)
;
(note there is still an ID column in the first table and the relationship table references it)
As Like It says in the comment, you're getting your tables mixed up, you've given us python code for StateTax, not SalesTaxRegion.
I've tested your StateTax code with Django 1.4 and Postgres 9.2 and I get the following -
-- DROP TABLE testing_statetax;
CREATE TABLE testing_statetax
(
name character varying(256) NOT NULL,
abbr character varying(64) NOT NULL,
rate integer NOT NULL,
CONSTRAINT testing_statetax_pkey PRIMARY KEY (abbr)
)
There's no additional id field added.

Adding values in my database via a ManyToMany relationship represented in admin.py

I've got a tiny little problem that, unfortunately, is taking all my time.
It is really simple, I already have my database and I created then modified models.py, and admin.py. Some staff users, who will need to enter values in my database, need the simpliest form to do so.
Here is my database :
-- Table NGSdb.line
CREATE TABLE IF NOT EXISTS `NGSdb`.`line` (
`id` INT NOT NULL AUTO_INCREMENT ,
`value` INT NOT NULL ,
PRIMARY KEY (`id`) )
ENGINE = InnoDB;
CREATE UNIQUE INDEX `value_UNIQUE` ON `NGSdb`.`line` (`value` ASC) ;
-- Table NGSdb.run_has_sample_lines
CREATE TABLE IF NOT EXISTS `NGSdb`.`run_has_sample_lines` (
`line_id` INT NOT NULL ,
`runhassample_id` INT NOT NULL ,
PRIMARY KEY (`line_id`, `runhassample_id`) ,
CONSTRAINT `fk_sample_has_line_line1`
FOREIGN KEY (`line_id` )
REFERENCES `NGSdb`.`line` (`id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_sample_has_line_run_has_sample1`
FOREIGN KEY (`runhassample_id` )
REFERENCES `NGSdb`.`run_has_sample` (`id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
-- Table NGSdb.run_has_sample
CREATE TABLE IF NOT EXISTS `NGSdb`.`run_has_sample` (
`id` INT NOT NULL AUTO_INCREMENT ,
`run_id` INT NOT NULL ,
`sample_id` INT NOT NULL ,
`dna_quantification_ng_per_ul` FLOAT NULL ,
PRIMARY KEY (`id`, `run_id`, `sample_id`) ,
CONSTRAINT `fk_run_has_sample_run1`
FOREIGN KEY (`run_id` )
REFERENCES `NGSdb`.`run` (`id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_run_has_sample_sample1`
FOREIGN KEY (`sample_id` )
REFERENCES `NGSdb`.`sample` (`id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
Here is my models.py :
class Run(models.Model):
id = models.AutoField(primary_key=True)
start_date = models.DateField(null=True, blank=True, verbose_name='start date')
end_date = models.DateField(null=True, blank=True, verbose_name='end date')
project = models.ForeignKey(Project)
sequencing_type = models.ForeignKey(SequencingType)
def __unicode__(self):
return u"run started %s from the project %s" % (self.start_date,self.project)
class Line(models.Model):
id = models.AutoField(primary_key=True)
value = models.IntegerField()
def __unicode__(self):
return u"%s" % str(self.value)
class RunHasSample(models.Model):
id = models.AutoField(primary_key=True)
run = models.ForeignKey(Run)
sample = models.ForeignKey(Sample)
dna_quantification_ng_per_ul = models.FloatField(null=True, blank=True)
lines = models.ManyToManyField(Line)
def __unicode__(self):
return u"Sample %s from run %s" % (self.sample, self.run)
And here is my admin.py :
class RunHasSamplesInLine(admin.TabularInline):
model = RunHasSample
fields = ['sample', 'dna_quantification_ng_per_ul', 'lines']
extra = 6
class RunAdmin(admin.ModelAdmin):
fields = ['project', 'start_date', 'end_date', 'sequencing_type']
inlines = [RunHasSamplesInLine]
list_display = ('project', 'start_date', 'end_date', 'sequencing_type')
As you can see, my samples are displayed in lines in the run form so that the staff can easily fullfill the database.
When I try to fill the database I have this error :
(1054, "Unknown column 'run_has_sample_lines.id' in 'field list'")
Of course, there are no field "lines" in my database ! It is a many to many field so I already created my intermediate table !
Okay okay ! So I tried to create the model for the intermediate table (run_has_sample_lines) and add a "through" to the ManyToManyField in the RunHasSample model. But, as I add manually the "through", I cannot use the ManyToMany field. The only way to add lines to the admin view is to stack them in lines... As you can see the samples are already in lines, it is impossible to put a new "inlines" in the already in lines samples...
Finally, I just tried to see what django had created with the manage.py sqlall.
I see that :
CREATE TABLE `run_has_sample_lines` (
`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY,
`runhassample_id` integer NOT NULL,
`line_id` integer NOT NULL,
UNIQUE (`runhassample_id`, `line_id`)
)
;
ALTER TABLE `run_has_sample_lines` ADD CONSTRAINT `line_id_refs_id_4f0766aa` FOREIGN KEY (`line_id`) REFERENCES `line` (`id`);
It seems that there are no foreign key on the run_has_sample table whereas I created it in the database in the first place. I guess that the problem is coming from here but I cannot resolve it and I really hope that you can...
Thank you very much !
you may wish to try a 'through' attribute on the many-to-many relationship and declare your intermediate table in Django.
I found where the problem is...
It is not a problem in the ManyToManyField but in the intermediate table. Django refused that my intermediate table doesn't have an unique id !
So, in the sql which created django, it created automatically an unique id named "id", but in my database I didn't create one (because the couple of two foreign key is usually enough).
Next time, I'll be more carefull.

Why django doesn't generate a constraint for many-to-many mapping as follows:

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.)