Want to add a one-to-one column to an existing table - python

I have a new field in the Client called note which has a one-to-one relation with Notes.
I want to be able to add the note column under the Client table in mysql. It does not work when I use python manage.py syncdb. So I would like to know how to add a one-to-one field in mysql to an existing table.
models.py
class Note(models.Model):
datetime = models.DateTimeField(default=datetime.now)
user = models.ForeignKey(User)
note = models.TextField()
def __unicode__(self):
return unicode(self.name)
class Client(models.Model):
note = models.OneToOneField(Note) # new
def __unicode__(self)
return unicode(self.user)

Syncdb doesn't change your database in order not to destroy your data. See django book.
You can update the database manually or use an automated migration tool (at your own risk) like South.
EDIT:
In django book, you can also read detailed instructions about manual changes along with SQL examples. Other useful information can be found in MySQL manual.

You didn't say what the application name is so I'll assume it is fooapp.
First look at the SQL Django would have used to create the relevant tables:
python manage.py sql fooapp
For additional fields run this sql command:
ALTER TABLE fooapp_client ADD ...
where ... is the field declaration you saw in the output of "manage.py sql fooapp"
Remember to also execute any index/constraint commands in the "manage.py sql fooapp" output that operate on the new field.

Related

Migrate tables in django from a read-only database

Is there a way to migrate all tables from an oracle read-only database to django?
So basically I don't want to make any modification to my database. I just want to extract information from it.
From what I found till now, is a way by using routers but I don't know how exactly to use it.
Thanks, any help will be appreciated
DB: oracle
Django version: 2.2.12
python: 3.6
cx-Oracle: 7.3.0
you should use model.Meta.managed=False
you will define a normal model and set this attribute in it's meta
class AModel(models.Model):
field1 = ...
field2 = ...
class Meta:
managed = False
db_table = "name_of_already_created_table"
if by router you mean Database routers it should only be used if you have more than one database to work with.
you should write your models based on the tables and columns that you have in your oracle db and add the managed=False to each of them separately.
so if you have for example three tables in your database you will write three separate models for it in your models.py file. this way django wont create the tables and just trys to read those tables also you need the db_table attribute and value of it should be the name of your table in the database

View Django User table from MySQL console

I want to view Django default User table from MySQL console.
I know to access from django shell or python by simply importing it.
from django.contrib.auth.models import User
is there a way to view it from MySQL console itself?
and where it will be located? i mean in which database django user table belongs?
Of course you can see it in the database.
As with all other models, unless instructed otherwise by using a db_table property in the Meta class, Django uses the naming schema appname_modelname for tables - so in this case the table is auth_user.
If you don't know and can't find the source, you can ask the model itself - ie User._meta.db_table.
The tables are located in the database which you have specified in settings.py. The django user table will be located at yourdbname.auth_user. All user defined models will be stored as yourdbname.appname_modelname
You can use "python manage.py dbshell" (in order to do this in linux, you need to install mysqlclient) and use "show tables;" and "select * from yourdb.table"

How to change Django's default Postgres database search directory

I am creating a Django web application and I am using Postgres for my database.
Under my project, I have a web application named 'home', and I created a table named 'myTable' in Postgres.
Whenever I try to save something in the table, Django automatically looks for the table called 'home_myTable' instead of 'myTable'. For example, if I do
python manage.py migrate
I get the following error:
django.db.utils.ProgrammingError: relation "home_myTable" does not exist
I have been working around this by manually giving Postgres commands using Psycopg2, but this is really annoying.
Is there a way to stop Django from automatically start looking for 'home_myTable' and instead make it search the table that I want?
You can set the db_table Meta option for you model.
class MyTable(models.Model):
...
class Meta:
db_table = 'mytable'
Unless you are dealing with a legacy database, I recommend that you define your models, create migrations, then let Django create the tables, instead of creating the tables manually as you are doing.

Django many to many relationship with built in "User" model

Scenario
I have a basic Django app in which users (django's authentication built in model) and reports have a many-to-many relationship.
The Problem
Django does not create a corresponding table to handle this relationship. My application is called reports. There is an error in the admin system upon trying to create a report and assign users to it. It tries to query the table reports_report_users and it fails as it does not exist.
models.py code
from django.db import models
from django.contrib.auth.models import User
class Report(models.Model):
name = models.CharField(max_length=30, blank=False)
users = models.ManyToManyField(User, related_name='reports')
def __unicode__(self):
return self.name
Attempted Solutions
Used this link as a reference: https://docs.djangoproject.com/en/1.4/topics/db/examples/many_to_many/
Ran manage.py syncdb about 300 times - ok, only once, but there were no errors and upon inspecting the SQLite db there were no additional tables created :(
It seems like you've added to the Report model after the first sync. Thus you're dealing with a migration, which django doesn't do natively.
First, Inspect the sql output, make sure that the create table instruction for your many to many relationship is there.
python manage.py sqlall
Assuming the problem is that this is a migration, which django doesn't handle natively, you've got three options:
1) Delete all db tables for this app, then run syncdb again.
2) Manually create the tables (fairly easy to copy paste the create sql from the sqlall command)
3) Start using a migration framework like South.
In the long run you'll appreciate the investment in learning south. In the short term, deleting the DB file is the fastest.-
Have you deleted your db file and run manage.py syncdb again?

Django - syncdb doesn't create tables

I added a many-to-many field to an existing model and was expecting syncdb to create a new table, but there's nothing there. This is what the model looks like:
class Author(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
email = models.EmailField()
def __unicode__(self):
return "{0} {1}".format(self.first_name, self.last_name)
class Book(models.Model):
title = models.CharField(max_length=100)
authors = models.ManyToManyField(Author)
def __unicode__(self):
return self.title
Running sql myapp prints the correct statements with the new table, but this is not reflected when I run syncdb. validate also returns no errors. Does anyone know what could be the matter here? Or a better diagnostic?
The syncdb command does not create many to many tables for existing models by design. This decision is explained on ticket 2229.
That leaves you with a few options.
If you don't have any data in your Book model, drop the table and rerun syncdb. Django will recreate the book table and the many to many table.
Use the dbshell command, and create the many to many joining table using the output of sql myapp.
If you're doing multiple schema migrations with Django, make friends with South.
I found this explanation at the django docs useful: SchemaEvolution.
The de facto standard for database migration is Django South.
Its not perfect, but, it works pretty well. You should always check(and edit if necessary) your migration file before running it, to make sure that it actually does what it supposed to do.
You can check out their tutorial here.
Also, if you run:
python manage.py inspectdb > somefile.txt
You can get quickly check out if your database structure is matching your django models.

Categories

Resources