I am using django and postgresql db to develop my project, the db has 3 schemas. And I am writing raw quires using connection string to fetch data and insert data into tables.
Example:
from django.db import connection
query = "select * from schema1.records"
cursor = connection.cursor()
cursor.execute(query)
output = cursor.fetchall()
Like way I am using in my all views.
I wanted to write test cases to my views, so i need to generate fixtures to test my views, how to I generate fixtures for schemas and tables. Please help.
Note: I did not write any models i just used raw queries in my whole project.
Run:
manage.py dumpdata help
This will show how to use loaddata to generate fixtures.
Related
I tried to use postgres database with pytest-django and I've encountered a problem. I have a fixture named populate_db which creates some records in the database. To check if pytest actually creates records, I put a 60-seconds sleep after creating the model objects and checked the panel admin but none of the created objects were present there. I think the pytest can't connect to my database and doesn't create any records in the database. Below are the functions that I have in my conftest.py file and I have another test file which tries to retrieve a database record from the API.
Here is my code for the populate_db fixture:
#pytest.fixture(autouse=True)
def populate_db():
sport = Vertical.objects.create(name='sport')
bazar = Vertical.objects.create(name='bazar')
time.sleep(60)
yield
Just a simple question.
After I connect my django app to a remote database, I don't need to use Model.py to create tables in the database, then what is the function for Model.py at that moment?
If you want to use the Django ORM, you'll need to create models in the models.py file that match your remote database. If you don't want django creating or deleting tables on this DB, the managed=False option needs to be set for each model.
https://docs.djangoproject.com/en/1.11/ref/models/options/#managed
As you said after running migrations all tables in models.py file will be created. Later on, if you want to do some database operations, you may be using Django ORM. If you don't have models.py you won't be able to do such operations.
For example:
To create an entry to the table MyModel.
from your_app.models import MyModel
MyModel.objects.create(<field_name>=<value>)
I hope this gives you some idea.
I have created a django project and now rendering templates. I have a mysql database already with loads of tables and data.
From what i saw in the tutorials, the model concept of python is interesting and easy however i am not able to use it here, as i have no models available i guess. Was assuming django would magically create models based on my db.
I have filled up settings.py with engine, db, username, host, port etc.,
Do i have to create models based on my tables?
This works thou:
db = MySQLdb.connect(user='root', db='dbBooks', passwd='1234', host='localhost')
cursor = db.cursor()
cursor.execute('SELECT bookname FROM books')
names = [row[0] for row in cursor.fetchall()]
db.close()
return render(request, 'index.html', {'bookNames': names})
inspectdb works fine now. (Django 1.7.1) Simply running manage.py inspectdb will create classes for all tables in database and display on console.
$ python manage.py inspectdb
Save this as a file by using standard Unix output redirection:
$ python manage.py inspectdb > models.py
Reference
There is an way by which Django will auto-magically create models based on tables using the inspectdb option of manage.py. A short guide is provided in Django Documentation itself on Integrating Django with a legacy database
In django models we have option named managed which can be set True or False
According to documentation the only difference this option makes is whether table will be managed by django or not. Is management by django or by us makes any difference?
Is there any pros and cons of using one option rather than other?
I mean why would we opt for managed=False? Will it give some extra control or power which affects my code?
The main reason for using managed=False is if your model is backed by something like a database view, instead of a table - so you don't want Django to issue CREATE TABLE commands when you run syncdb.
Right from Django docs:
managed=False is useful if the model represents an existing table or a database view that has been created by some other means. This is the only difference when managed=False. All other aspects of model handling are exactly the same as normal
When ever we create the django model, the managed=True implicitly is
true by default. As we know that when we run python manage.py makemigrations the migration file(which we can say a db view) is
created in migration folder of the app and to apply that migration i.e
creates the table in db or we can say schema.
So by managed=False, we restrict Django to create table(scheme, update
the schema of the table) of that model or its fields specified in
migration file.
Why we use its?
case1: Sometime we use two db for the project for
example we have db1(default) and db2, so we don't want particular
model to be create the schema or table in db1 so we can this or we can
customize the db view.
case2. In django ORM, the db table is tied to django ORM model, It
help tie a database view to bind with a django ORM model.
Can also go through the link:
We can add our raw sql for db view in migration file.
The raw sql in migration look like: In 0001_initial.py
from future import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.RunSQL(
CREATE OR REPLACE VIEW app_test AS
SELECT row_number() OVER () as id,
ci.user_id,
ci.company_id,
),
]
Above code is just for overview of the looking of the migration file, can go through above link for brief.
I want to select data from a database table that is not part of my Django project. I added the database connection info to the settings file and I can do raw sql queries against it to pull the data. However, I would like to create a model for that table and be able to access the data as I would any other Django model data.
Is this possible? I can find any documentation on that.
The Django: Multiple Databases page contains good information on this topic. After you have configured your databases in settings.py, you can use .using() to specify the database you wish to query.
Examples from the documentation:
>>> # This will run on the 'default' database.
>>> Author.objects.all()
>>> # So will this.
>>> Author.objects.using('default').all()
>>> # This will run on the 'other' database.
>>> Author.objects.using('other').all()
sure, you just have to use
SomeObject.objects.using('database_name').all()
to do your queries