Django Foreign Key not working - python

Edit:Django version 1.6.1
I keep getting this error when trying to create a RedditPost object through the admin:
no such column: subreddit_id
The subreddit_id error references RedditPost.subreddit (not Subreddit.subreddit) and then adds an _id at the end for some reason.
There's no problem with the reference. When trying to create a RedditPost from admin, the drop down menu for Subreddits shows all the available Subreddits objects.
class Subreddit(models.Model):
subreddit = models.CharField(max_length=100, primary_key=True)
title = models.CharField(max_length=100, null=False)
def __unicode__(self):
return smart_unicode(self.subreddit)
class RedditPost(models.Model):
comments_link = models.CharField(max_length=256, primary_key=True)
submitted_link = models.CharField(max_length=256, null=False)
rank = models.IntegerField(null=False)
title = models.CharField(max_length=100, null=False)
reddit_timestamp = models.DateTimeField(null=False)
updated_at = models.DateTimeField(auto_now_add=True, auto_now=True)
subreddit = models.ForeignKey('Subreddit')
RESOLVED/SOLUTION: I ended using "flush" which didn't clear up the databases when I made changes (I wasn't using any migrations). I had to use:
python manage.py sqlclear "app_name" | python manage.py dbshell
To completely clear the database and then I had to follow this link(Django South error with initial migration) to do the migration correctly.

_id is automatically added by Django. there are reasions for it.
your db table RedditPost doesnot just have this column whatsoever..
after changing the table (by adding this new column), do:
if django version < 1.7: (south needs to be installed)
python manage.py schemamigration yourapp --auto
python manage.py migrate yourapp
if django version >= 1.7:
python manage.py makemigrations
python manage.py migrate

I had the same problem. Delete your db.sqlite3 file. Then on the terminal,
python3 manage.py makemigrations
python3 manage.py migrate
That's it. But your all saved database values will be deleted.

Related

Makemigrations and migrate in Django

I have a problem in the Django
For example:
In Definition of models. i have :
class Social_Network(models.Model):
Name = models.TextField(null=False)
Addresses = models.TextField(null=False)
And after running
python manage.py makemigrations
python manage.py migrate
Until this part everything its ok
My problem is starting now. When i want to change (Social_Network) models.
class Social_Network(models.Model):
Id = models.TextField(null=False)
Name = models.TextField(null=False)
Addresses = models.TextField(null=False)
I inserted 'Id' to 'social network' models
And after running
python manage.py makemigrations
python manage.py migrate
I encounter the following error
Please Help me
For convenience, each model has an AutoField named id by default unless you explicitly specify primary_key=True on a field in your model. See the documentation for AutoField for more details.

After Add New model.How to Django Table Migrate without losing data

class UserSubStatus(models.Model):
msisdn = models.CharField(max_length=200)
category = models.CharField(max_length=200, null=True, blank=True)
validity = models.IntegerField(default=1,null=True,blank=True)
sub_status = models.IntegerField(default=0)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
ordering = ['-created_at']
db_table = "user_sub_status"
I add this table on my model.py file. How add this "user_sub_status" table on my database without losing any data.
Hello Dear
First run the following command:
python manage.py makemigrations your_app_name
than run this command:
python manage.py migrate your_app_name
NB: I hope, "user_sub_status" will be added to your database without losing data.
run makemigrations and migrate as you did before. If you do not erase previous migrations files then by running makemigrations new migrations files will add to migrations folder and by migrate new tables or columns for previous tables will add to your database and there will be no problem with your stored data
First, you have to run makemigrations command which is responsible for creating new migrations based on the changes you have made to your models.
python manage.py makemigrations
Then you have to run a migration command which is responsible for applying and unapplying migrations that are created by the above command.
python manage.py migrate
With the help of above both command, your table "user_sub_status" will be added in your database without losing any data from your database.

Use Django Migrations to delete a table

I am moving from Rails to Django and have an existing database. I created models.py via python manage.py inspectdb > models.py, made changes, and tested some endpoints. Everything seems fine.
I then ran python manage.py makemigrations and migrate to make the initial django mirgation.
I noticed an old Rail's specific Model / table called ArInternalMetadata / ar_internal_metadata. I figure I could easily remove the table by simply removing the model from models.py and rerun makemigrations however when I do that, django just says No changes detected. Running migrate doesn't remove the table either.
Figured it out. When inspectdb creates Models from an existing database, it sets managed in the Meta inner class to False by default.
class AssetCategories(FacadeModel):
created_at = models.DateTimeField()
updated_at = models.DateTimeField()
name = models.CharField(max_length=255)
deleted_at = models.DateTimeField(blank=True, null=True)
class Meta:
managed = False
db_table = 'asset_categories'
Per the Django 2.1 Docs this will prevent deletion from happening
If False, no database table creation or deletion operations will be performed for this model
Removing managed = False from the Meta class allows makemigrations / migrate to delete the table.

Django - Can we erase migration folder?

I have a class like this (I didn't know about abstract class at the beginning):
class Client(models.Model):
company_name = models.CharField(max_length=50)
referrer = models.ForeignKey(User, null=True, blank=True)
address = models.CharField(max_length=400, blank=True)
class Customer(Client):
def __str__(self):
return "{company:s}".format(company=self.company_name)
I tried to add abstract class to client, did the makemigrations but migrate crash with this message:
django.core.exceptions.FieldError: Local field 'address' in class 'Customer' clashes with field of similar name from base class 'Client'
I tried to restart from scratch because I don't need migration right now and delete the folder.
I run manage.py migrate and It tells me that I didn't have auth_user table. Then I use manage.py migrate auth then manage.py migrate and it works !
Cool, almost, my django project is now running but when I launch the test I still have the issue:
can't find auth_user table...
I guess test didn't create the migrate auth for the test database.
What did I do wrong?

Setting database with django

I created a db with such tracks.models:
class Song(models.Model):
title = models.CharField(max_length=30)
album = models.ForeignKey(Album)
def __unicode__(self):
return self.title
and used
python manage.py sqall tracks
python manage.py syncdb
but then I changed models to
class Song(models.Model):
songid = models.CharField(max_length=30)
title = models.CharField(max_length=30)
album = models.ForeignKey(Album)
def __unicode__(self):
return self.title
and did
python manage.py sqall tracks
python manage.py syncdb
again. Output of sqall:
BEGIN;
CREATE TABLE "tracks_song" (
"id" integer NOT NULL PRIMARY KEY,
"songid" varchar(30) NOT NULL,
"title" varchar(30) NOT NULL,
"album_id" integer NOT NULL REFERENCES "tracks_album" ("id")
)
;
CREATE INDEX "tracks_song_6781e42a" ON "tracks_song" ("album_id");
COMMIT;
syncdb:
Creating tables ...
Installing custom SQL ...
Installing indexes ...
Installed 0 object(s) from 0 fixture(s)
But whenever I tried to access tracks.models.Song.all() it said:
OperationalError: no such column: tracks_song.songid
So I decided to
python manage.py flush
python manage.py sqall tracks
python manage.py syncdb
(same output)
But problem hasn't gone and there's still no such column: tracks_song.songid.
What's the problem behind it?
python manage.py sqlall app-name will only print SQL sentences, not create or change database structures, that is to say, it's used to check or tell you what django actually do in databases. Howerver, django version<1.7 doesn't track changes of class in models.py(newly increased or delete existed class could be detected and syncdb), but you can use south, or django 1.7 to do such thing.
python manage.py flush will IRREVERSIBLY DESTROY all data, but not change tables in database.
South: http://south.aeracode.org/
Django 1.7: https://docs.djangoproject.com/en/dev/releases/1.7/#django-1-7-release-notes-under-development
you should also notice that if you only need an id field, class Song has a default AutoField id, just use song.id Django models Quick Example

Categories