Is it possible to use Django but without models?
Instead of models I want to use raw sql queries with help of mysql cursor.
I want to implement Car Rental site to rent a car. There will be three tables: Cars, Users, Orders. Anyone can sign up on the webpage, sign in and make orders.
The only limitation is that a have to do this using raw sql queries so I think that I have to avoid using models.
Is this even possible?
I'm new to Django and this might be dump question but need to know cause this is my academic project.
Is this even possible?
Yes that is possible, but a lot of ways how Django can help with webdevelopment are based on its models. For example based on a model Django can make a ModelForm [Django-doc] to automate rendering HTML forms that map to the model, validating user input, and saving it to the database. You can still use a simple Form [Django-doc], but then you need to implement the validation, etc. yourself.
Class-based views like a ListView [Django-doc], DetailView [Django-doc], CreateView [Django-doc], etc. can automate a lot of the logic based on a model. These can then automatically query for the records of the model, or construct a form to create a new record. Often customizing such view to is not much effort. If you however do not define such models, you will need to implement a lot of the logic yourself.
The Django documentation has a section about executing custom SQL queries directly that explains how to use the connection configured in the settings.py to perform raw queries together with tips to avoid SQL injection.
That being said, without models, Django probably can offer approximately only as much help as Flask, so in that case there is likely not a clear advantage to use Django over Flask, especially since for small applications, a Flask application is very minimal.
Related
How can I access a MySQL view in Django?
I find it hard to believe that I am the first to want to do this with Django, but because both Django and MySQL use the term 'view' the search results have not been helpful. I have read the Django documentation on running raw SQL queries and accessing stored procedures, but it doesn't quite solve my particular need.
Basically, there are several MySQL views in the database that I need to manage/access via Django like I can with tables. I realize that I can access views by running raw SQL queries in Django, but I value the control Django models and migrations provide and would like to be able to do the same with views.
Ideally, I would like the official Django way of doing this but if that doesn't exist I would also value your hacks/workarounds for this.
I have a few databases in MongoDB that I want to create models for dynamically, since there are many databases and I cannot do it manually. Questions:
What should my models.py look like? (Does inspectdb work with mongodb databases or only SQL based dbs?)
Since the database models are created dynamically, how do I code the serializer class to return the dynamic fields?
Thanks in advance.
Django supports an object-relational mapper, that is aimed at traditional relational databases. While there are a number of mongodb packages for Django, none of them support inspectdb to construct your models. Either way, inspectdb is a kludge designed as a one of process to help a one-of migratation away from a legacy system, i.e. you'd build your models.py file once and never run inspectdb again. This is not what you want to do, as you seem to want dynamic models that can be added or altered at runtime.
On the bright side, Django MongoDB Engine has some support for arbitrary embedded models within pre-defined models. But even then they don't seem too supportive of it:
As you can see, generic embedded models add a lot of overhead that bloats up your data records. If you want to use them anyway, here’s how you’d do it...
In summary, try to build your models as best you can to actually match your requirements. If you know nothing about your models ahead of production, then perhaps Django isn't the right solution for you.
Recetly I've seen an app powered with django and mongodb as backend,thing is that app doesn't have a models.py file.All the datas are inserted directly in views.py.I Just need a little clarification about this particular things "Using django without models.py with mongodb."
models.py is the Django ORM way of inspecting a fixed relational schema and generating the relevant SQL code to initialize (or modify) the database. "ORM" stands for "Object-Relational Mapping".
Mongo is not relational, hence you don't need this type of schema.
(Of course, that can cause a lot of other problems if the needs of your project change later...)
But you don't need a relational schema since you're not using a relational DB.
A short answer
models.py is the ORM that comes free with django.
ORM relates your SQL schema into oopsy objects.
You can read more about ORM here-> https://en.wikipedia.org/wiki/Object-relational_mapping.
When using a noSQL, you can push objects directly into DB. So, you do not really need an ORM.
That said, whether to use it or not is a debatable part.
PS. even while using SQL, some people prefer other ORMs instead of django's built-in models.
I have a typical Django project with one primary database where I keep all the data I need.
Suppose there is another DB somewhere with some additional information. That DB isn't directly related to my Django project so let's assume I do not even have a control under it.
The problem is that I do ont know if I need to create and maintain a model for this external DB so I could use Django's ORM. Or maybe the best solution is to use raw SQL to fetch data from external DB and then use this ifo to filter data from primary DB using ORM, or directly in views.
The solution with creating a model seems to be quite ok but the fact that DB isn't a part of my project means I am not aware of possible schema changes and looks like it's a bad practice then.
So in the end if I have some external resources like DBs that are not related to but needed for my project should I:
Try to create django models for them
Use raw SQL to get info from external DB and then use it for filtering data from the primary DB with ORM as well as using data directly in views if needed
Use raw SQL both for a primary and an external DB where they intersect in app's logic
An alternative is to use SQLAlchemy for the external database. It can use reflection to generate the SQLAlchemy-equivalent of django models during runtime.
It still won't be without issues. If your code depends on a certain column, it would still break if that column is removed or changed in an incompatible way. However, it will add a bit more flexibility to your database interactions, e.g. a Django model would definitely break if an int column is changed to a varchar column, but using database reflection, it will only break if your code depends on the fact that it is an int. If you simply display the data or something, it will remain fully functional. However, there is always a chance that a change doesn't break the system, but causes unexpected behaviour.
If, like Benjamin said, the external system has an API, that would be the preferred choice.
I suggest you to read about inspectdb and database routers. It's possible to use the django ORM to manipulate a external DB.
https://docs.djangoproject.com/en/1.7/ref/django-admin/#inspectdb
I would create the minimal django models on the external databases => those that interact with your code:
Several outcomes to this
If parts of the database you're not interested in change, it won't have an impact on your app.
If the external models your using change, you probably want to be aware of that as quickly as possible (your app is likely to break in that case too).
All the relational databases queries in your code are handled by the same ORM.
I'm building a rather large project, that basically consists of this:
Server 1:
Ice based services.
Glacier2 for session handling.
Firewall allowing access to Glacier2.
Server 2:
Web interface (read, public) for Ice services via Glacier2.
Admin interface for Ice services via Glacier 2.
The point I'm concerned with is the web interface. I want to use Django, because it's both written in python and has that incredibly useful automatic admin panel generator.
The web interface doesn't access any database. It connects to an Ice service on Server #1 via the Glacier2 router and uses the API exposed by those services to manipulate data.
And as you probably know, the admin generation in Django depends on the use of Django's ORM; which I'm not using since I have no database to access.
So I need to generate the admin panel, but, instead of having an standard data access like the ORM normally does, I need to intercept any "db-access" calls and transform them into Ice service calls, and then take the service's output (if any), transform it into whatever the ORM normally returns and return control to Django.
Anyone knows how I could do this? what would I need to subclass? Any specific ideas?
Thanks for your time.
I think there might be a simpler way than writing custom ORMS to get the admin integration you want. I used it in an app that allows managing Webfaction email accounts via their Control Panel API.
Take a look at models.py, admin.py and urls.py here: django-webfaction
To create an entry on the admin index page use a dummy model that has managed=False
Register that model with the admin.
You can then intercept the admin urls and direct them to your own views.
This makes sense if the add/edit/delete actions the admin provides make sense for your app. Otherwise you are better off overriding the admin index or changelist templates to include your own custom actions
The real power of the contrib.admin is django Forms. In essence, the admin tool is basically auto-generating a Form to match a Model with a little bit of urls.py routing thrown in. In the end it would probably just be easier to use django Forms apart from the admin tool.
you can "mock" some class so it look like a model but it does proxy to your APIs
f.e.
class QuerysetMock(object):
def all():
return call_to_your_api()
[...]
class MetaMock(object):
def fields():
return fields_mock_objects..
verbose_name = ''
[...]
class ModelMock(object):
_meta = MetaMock()
objects = QuerysetMock()
admin.site.register(ModelMock)
This may work.. but you need to do a lot django.model compatible stuff
The django ORM has a pluggable backent, which means that you can write a backend for things that aren't RDBMSes. It's probably a rather large task, but a good place to get started is with Malcolm Tredinnick's talk from DjangoCon 2008, Inside the ORM.
Otherwise, you could bypass the ORM altogether, and write the forms manually for the access you need.