I have the following model
from django.db import models
class Todo(models.Model):
content = models.CharField(max_length=100)
created_at_one: models.DateField(auto_now_add=True)
finished_at: models.DateField(null=True)
is_completed: models.BooleanField(default=False)
list = models.ForeignKey(
"TodoList", related_name="todos", on_delete=models.CASCADE)
class TodoList(models.Model):
title: models.CharField(max_length=20)
created_at: models.DateField(auto_now_add=True)
Then when I run python manage.py makemigrations and python3 manage.py migrate, there is no error. But when I check the tables created, some columns are missing.
I run .schema app_todo to check the tables of Todo
CREATE TABLE IF NOT EXISTS "app_todo" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "content" varchar(100) NOT NULL, "list_id" bigint NOT NULL REFERENCES "app_todolist" ("id") DEFERRABLE INITIALLY DEFERRED);
CREATE INDEX "app_todo_list_id_c59d99ef" ON "app_todo" ("list_id");
Only id, content and list_id are created and three columns missing.
For TodoList:
CREATE TABLE IF NOT EXISTS "app_todolist" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT);
title and create_at are missing.
Please let me know if there is additional information that I should provide.
Thanks a lot!
You probably made a typo write writing your model. You must not use : but = when declaring your fields. It should be :
from django.db import models
class Todo(models.Model):
content = models.CharField(max_length=100)
created_at_one = models.DateField(auto_now_add=True)
finished_at = models.DateField(null=True)
is_completed = models.BooleanField(default=False)
list = models.ForeignKey(
"TodoList", related_name="todos", on_delete=models.CASCADE)
class TodoList(models.Model):
title = models.CharField(max_length=20)
created_at = models.DateField(auto_now_add=True)
When using : you may create some class attributes but that are not considered by Django for building database models.
Related
i have set Primary key in my Django Models and but When i am inserting data into MongoDB database ,the primary key is not inserted.by default Django is inseting primary key but in my case its not.i Don't know what i am Doing Wrong Here.i am using below code
My Model.py
class CategoryModel(models.Model):
id = models.AutoField(primary_key=True) #if i don't use this line,django should insert primary by default.i my other app its inserting by default
category_name = models.CharField(max_length=255)
when i insert data into my CategoryModel,the primary key is not inserted.i am using Following code to insert data
Views.py
CategoryModel.objects.create(
category_name =request.POST['category_name']
)
Here,category_name is inserted but Primary key is not inserted.I don't know what is the issue.i Will be thankful if any one can help me with this issue.
a = CategoryModel()
a.category_name = request.POST['category_name']
a.save()
and ID you must use some other name for id because id is default django field
id_out = models.BigAutoField(primary_key=False, db_index=True, unique=True, editable=False)
Depends on what kind of id you're looking for, I typically use uuid4:
from uuid import uuid4
from django.db import models
def gen_uuid() -> str:
"""Return a str representation of a uuid4"""
return str(uuid4())
class CategoryModel(models.Model):
uid = models.CharField(
unique=True,
primary_key=True,
default=gen_uuid,
max_length=36,
help_text="Example: c8daa3ac-3dd0-44e9-ba2a-b0cbd1c8d8ae.",
)
category_name = models.CharField(max_length=255)
This allows to customize your ID. However if you are sure to use UUID like above I'd recommend this implementation as it uses the proper field:
from uuid import uuid4
from django.db import models
class CategoryModel(models.Model):
uid = models.UUIDField(
unique=True,
primary_key=True,
default=uuid4,
help_text="Example: c8daa3ac-3dd0-44e9-ba2a-b0cbd1c8d8ae.",
)
category_name = models.CharField(max_length=255)
As it is explained by the Autofield doc, you do not need to set your id if you wish to have the default id behavior: Autofield
It should insert your id automatically if you don't specify anything.
I have two models:
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Category(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="categories")
name = models.CharField(max_length=30, unique=True, primary_key=True)
class Todo(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='todos')
# TODO: Add confirmation before deleting category
category = models.ForeignKey(Category, on_delete=models.CASCADE,
related_name="todos_in_category", null=True)
item = models.CharField(max_length=50)
added = models.DateTimeField(auto_now_add=True)
completed = models.BooleanField(default=False)
Previously, Category's PK was the default id, however, I changed it to the name field. When I ran the migrations, i received the operational error. Thinking that it was perhaps due to a conflict between the existing id fields and the new primary key, I cleared the data in the database but with no success. Any ideas as to what could be the issue here? Thanks!
I have two models as shown below. ArticlePost is related to Article by a Foreign Key. I'm wanting to remove name as a primary key on Article and instead have the Django default id field. What is the best steps to do this so that all related ArticlePosts will maintain the correct Foreign Key to Article?
class Article(models.Model):
name = models.CharField(max_length=200, primary_key=True)
class ArticlePost(models.Model):
article = models.ForeignKey(Article, null=False, db_index=True)
created_at = models.DateTimeField(auto_now_add=True)
comment = models.TextField(blank=True)
I have the following code in my models.py file:
from django.db import models
from django.db.models import permalink
class Page(models.Model):
name = models.CharField(max_length=100,db_index=True, unique=True)
slug = models.SlugField(max_length=100,db_index=True, unique=True)
def __unicode__(self):
return '%s' % self.name
class Category(models.Model):
name = models.CharField(max_length=100, db_index=True, unique=True)
slug = models.SlugField(max_length=100, db_index=True, unique=True)
def __unicode__(self):
return '%s' % self.name
class Post(models.Model):
title = models.CharField(max_length=100, unique=True, db_index=True)
body = models.TextField()
post_date = models.DateField(db_index = True, auto_now_add=True)
category = models.ForeignKey('board.Category')
page = models.ForeignKey('board.Page')
def __unicode__(self):
return '%s' % self.title
#permalink
def get_absolute_url(self):
return "/%i/%i" % Page.slug, self.id
When I try to add a Post object in the admin page (I configured the admin.py too), I get the following error:
no such column: board_category.name
I did my research and tried dropping the table and doing syncdb again but somehow it still shows this error.
So I listed my tables:
CREATE TABLE "board_page" (
"id" integer NOT NULL PRIMARY KEY,
"name" varchar(100) NOT NULL UNIQUE,
"slug" varchar(100) NOT NULL UNIQUE
)
;
CREATE TABLE "board_category" (
"id" integer NOT NULL PRIMARY KEY,
"name" varchar(100) NOT NULL UNIQUE,
"slug" varchar(100) NOT NULL UNIQUE
)
;
CREATE TABLE "board_post" (
"id" integer NOT NULL PRIMARY KEY,
"title" varchar(100) NOT NULL UNIQUE,
"body" text NOT NULL,
"post_date" date NOT NULL,
"category_id" integer NOT NULL REFERENCES "board_category" ("id"),
"page_id" integer NOT NULL REFERENCES "board_page" ("id")
)
;
CREATE INDEX "board_post_896eb94b" ON "board_post" ("post_date");
CREATE INDEX "board_post_6f33f001" ON "board_post" ("category_id");
CREATE INDEX "board_post_3fb9c94f" ON "board_post" ("page_id");
I'm not exactly an expert in SQL but I can clearly see that the board_page.name column exists so I really have no idea why this is giving me an error.
And the strangest thing is that adding another page or category actually works....
--EDIT
from django.contrib import admin
from board.models import Page, Post, Category
class PageAdmin(admin.ModelAdmin):
#fields = ['name','slug']
pass
class PostAdmin(admin.ModelAdmin):
#fields = ['title','body','category','page']
pass
class CategoryAdmin(admin.ModelAdmin):
#fields = ['name','slug']
pass
admin.site.register(Page, PageAdmin)
admin.site.register(Post, PostAdmin)
admin.site.register(Category, CategoryAdmin)
syncdb will only create tables for models which have not yet been installed. It will never issue ALTER TABLE statements to match changes made to a model class after installation.
better use South to migrate the changes of your models.
first migration with:
python manage.py schemamigration yourapp --initial
python manage.py migrate yourapp
other migrations:
python manage.py schemamigration yourapp --auto
python manage.py migrate yourapp
If you add something to your models and after that you did not sync, this happens.
If you are in beginning for your project, I recommend to remove your db and recreate it and then:
python manage.py syncdb
Otherwise use South.
http://south.readthedocs.org/en/latest/
It's interesting but sometimes rebooting the server helps. It worked for me a few times in past.
I've got these two classes:
class Bill(models.Model):
date = models.DateField()
total_amount_chf = models.DecimalField('Cost (in CHF)', max_digits=10, decimal_places=2)
class ProjectParticipation(models.Model):
project = models.ForeignKey('Project')
user = models.ForeignKey(User)
is_admin = models.BooleanField()
bill = models.OneToOneField(Bill, on_delete=models.SET_NULL, null=True, blank=True)
When I'm now constructing the SQL-database I get the following field in the table for the ProjectParticipation:
bill_id integer NOT NULL,
CONSTRAINT expenses_projectparticipation_bill_id_fkey FOREIGN KEY (bill_id)
REFERENCES expenses_bill (id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION DEFERRABLE INITIALLY DEFERRED,
And now when I want to insert a ProjectParticipation without Bill I get a "null value in column "bill_id" violates not-null constraint".
What to do against it?
May be you have added the Null Constraint later after syncing the database. Delete the database and re-sync the database (if you are not using Django-South otherwise make sure you have migrated the schema changes)