'authorid' is a foreign key to the Django 'User' model. After running 'makemigrations' and 'migrate' I can not see this field in the sqlite shell.
Here are my models,
class TopicModel(models.Model):
topic = models.CharField(max_length = 100)
topicAuthor = models.CharField(max_length = 100)
authorid = models.ForeignKey(User, related_name = 'id_of_author')
views = models.PositiveIntegerField(default = 0)
def __str__(self):
return self.topic
class PostModel(models.Model):
post = HTMLField(blank = True, max_length = 1000)
pub_date = models.DateTimeField('date published')
author = models.CharField(max_length = 30)
topicid = models.ForeignKey(TopicModel, related_name = 'posts')
def __str__(self):
return self.post
As you can see postmodel also has a foreign key to the topicmodel and there is no problem with this foreign key.
After migration the migrate file 0001_initial.py looks like this,
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import tinymce.models
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='PostModel',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('post', tinymce.models.HTMLField(blank=True, max_length=1000)),
('pub_date', models.DateTimeField(verbose_name='date published')),
('author', models.CharField(max_length=30)),
],
),
migrations.CreateModel(
name='TopicModel',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('topic', models.CharField(max_length=100)),
('topicAuthor', models.CharField(max_length=100)),
('views', models.PositiveIntegerField(default=0)),
('authorid', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='id_of_author', to=settings.AUTH_USER_MODEL)),
],
),
migrations.AddField(
model_name='postmodel',
name='topicid',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='posts', to='crudapp.TopicModel'),
),
]
In the sqlite shell the postmodel shows the field with the foreign key, which is topicid_id
sqlite> PRAGMA table_info(crudapp_postmodel);
0|id|integer|1||1
1|pub_date|datetime|1||0
2|author|varchar(30)|1||0
3|topicid_id|integer|1||0
4|post|text|1||0
But when I do the same with the topicmodel, the field with the foreign key doesn't exist, so there is no authorid field.
sqlite> PRAGMA table_info(crudapp_topicmodel);
0|id|integer|1||1
1|topic|varchar(100)|1||0
2|topicAuthor|varchar(100)|1||0
3|views|integer unsigned|1||0
Solution: As suggested by Alasdair I deleted the sqlitedb file and changed the fields from from topicid and authorid to topic and author.
Your current migration should create the foreign keys. My guess is that you updated the migration file after you had already created the crudapp_topicmodel table in the database.
If you don't have any important data yet, the easiest fix is to delete your sqlite file and rerun ./manage.py migrate.
Related
I did lot's of try, catch on this issue and basically still not find the core problem but this is what I got for now.
in the settings.py I am turning on the USE_TZ = True TIME_ZONE = 'UTC' and creating a model like below.
class Plan(models.Model):
name = models.CharField(max_length=100)
code = models.CharField(max_length=100)
price = models.IntegerField()
description = models.TextField(null=True, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.name
when I try to makemigration for this is no problem. Here is the first migration file of Plan model
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Plan',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=100)),
('code', models.CharField(max_length=100)),
('price', models.IntegerField()),
('description', models.TextField(blank=True, null=True)),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
],
),
]
Now, when I try to migrate this file. There are two table created in the DB. one for django_migrations and the other is Plan model. After running migrate command. error follows.
raise ValueError('Not naive datetime (tzinfo is already set)') ValueError: Not naive datetime (tzinfo is already set)
first plan model causing this error. But when I delete the django_migrations table from DB. error not recurring. it's look like even if I use USE_TZ = True django not inserting date correctly.
models.py
class Country(models.Model):
name = models.CharField(max_length=50, validators=[validate_name, ])
class Meta:
managed = False
db_table = 'countries'
def __str__(self):
return self.name
0001_initial.py
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Country',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=50, validators=[countries.validators.validate_name])),
],
options={
'db_table': 'countries',
'managed': False,
},
),
]
sql
(venv) michael#michael:~/Documents/PyCharmProjects/db/db$ python manage.py sqlmigrate countries 0001_initial
BEGIN;
--
-- Create model Country
--
-- (no-op)
COMMIT;
Could you tell me whether this sql reflects the model or not? If not, how can it happen? And will it produce in the database?
There is no sql to apply to the db because of managed = False.
That is, running migrate does not change the db.
Python 3.10.4
Django 4.0.5
PostgreSQL 14
When I start "python manage.py makemigrations" i got the file "0001_initial.py" but all Fields, except autofields, are missing.
models.py
from django.db import models
# Create your models here.
class Username(models.Model):
#id = models.AutoField(primary_key=True)
username: models.CharField(max_length=100)
class Carrier(models.Model):
#id = models.AutoField(primary_key=True)
carriername: models.CharField(max_length=100)
desc: models.TextField()
0001_initial.py
# Generated by Django 4.0.5 on 2022-06-29 13:18
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Carrier',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
],
),
migrations.CreateModel(
name='Username',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
],
),
]
First, you must know that Django By default adds the id field to the models ...
Try to Delete the migration file and
you must use the = not the :
so it will be like this
class Username(models.Model):
username=models.CharField(max_length=100)
class Carrier(models.Model):
carriername = models.CharField(max_length=100)
desc = models.TextField()
rerun manage.py makemigrations and it Should work
I created a dummy project just to test the new field JSONField of Django but the column doesn't not appear to be created (I am using Postgresql).
class Author(models.Model):
name = models.CharField(max_length=50)
description = models.TextField()
slug = models.SlugField()
details = models.JSONField()
class Meta:
verbose_name = "Author"
def __str__(self):
return self.name
If i go to the database, the column is not created -- screenshot
When i go to the admin view page of the table Author i get the following error -- screenshot
The error in the admin panel is understandable: you cannot view a column that does not exist. Do you guys have the same error? I can't find this error with JSONField anywhere.
Thanks
Note: This is my first post.
EDIT I create all the fields in the same time. Migration file:
# Generated by Django 3.1.3 on 2020-11-20 10:35
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Author',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=50)),
('description', models.TextField()),
('slug', models.SlugField()),
('details', models.JSONField()),
],
options={
'verbose_name': 'Author',
},
),
]
Migrated with sucess:
Migrations for 'blog':
blog/migrations/0001_initial.py
- Create model Author
check that you migration was applied to the right database
I have a contact information model/form which I want to add a contacttype foreign key to that should be displayed in a drop down menu:
models.py
class ContactType(models.Model):
contact_type = models.CharField(max_length=50)
class Contact(models.Model):
contact_name = models.CharField(max_length=200)
contact_email = models.CharField(max_length=200, validators=[validators.validate_email])
contact_type = models.ForeignKey(ContactType, default='General Enquiry')
forms.py
class ContactForm(forms.ModelForm):
# contact_type = forms.ModelChoiceField(queryset=ContactType.objects.all())
class Meta:
model = Contact
fields = ['contact_name', 'contact_email']
If I leave the contact_type variable where it is, I get the following error:
no such table: contact_contacttype
Here is my last migration:
dependencies = [
('contact', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='ContactType',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('contact_type', models.CharField(max_length=50)),
],
),
migrations.AddField(
model_name='contact',
name='contact_type',
field=models.ForeignKey(default='General Enquiry', on_delete=django.db.models.deletion.CASCADE, to='contact.ContactType'),
),
]
whereas if I move it into meta class (should I?) nothing renders into the template.
So my question is, is a foreign key the appropriate relationship? And if so, how should I add the ModelChoiceField to the ContactForm