Django Requests and Concurrency - django

I'm a little bit confused as to a few concepts regarding Django and concurrency. Suppose two users append data to the database or make a query at the same time. How do I determine what data to render for the user? I know each model has an id, but how is that associated with the user? Is this done mainly through the primary key field which you can add to Django views, or is this already done using Django sessions, and thus no need for management of primary keys or Django model ids? I've been researching for hours but I still don't understand this concept.

Related

How to dynamically swap default database on the model manager in django?

I am creating a project in django and django rest framework. Its an api for an angular app. The database setup consists of multiple databases. one is default database, all the django tables reside in this database; rest of the databases belong to a type of a user, each user is supposed to have a separate database. So, all the user related data goes to its separate database. To implement the selecting database dynamically, user object has an extra field to store the database to write to.
from django.contrib.auth.models import AbstractUser
class CustomUser(AbstractUser):
"""Custom User model."""
database= models.CharField(max_length=9)
Reason for doing this was performance improvement as each database is separate, ListView and DetailView would work faster than if the data was stored in the one database only.
I know I can choose a database to store by using the using method on the model manager. In the rest api things work fine and data is being stored in their separate databases, but I end up overriding methods that django has defined. Its adding development cost to the project. Foreign keys and ManytoMany keys needs to be resolved with the current database of the user, which is not happening as I have customized the database setup. Also, my code cant be as good as theirs :p , as they have written django over the course of many years.
I have overwritten many querysets already, but django still uses default database many times. If only I could use the request object in the model manager of django models to swap the default database on per request basis, things would be different i think.
My questions are -
Is there a way to access the request object in the model manager? I could do something to the effect of below code.
class CustomManager(models.Manager):
def get_queryset(self, request):
return super(CustomManager, self).using(request.user.database).get_queryset()
Model manager has _db property that could be used to select database. Would overriding it is advised? if yes, how and where in the code?
Is there a better way to implement the separate databases?
Thanks in advance.
Regards
Using a database router is recommended in Django docs, but the problem is it only accesses the model class.
Found a couple of questions related to the problem of switching databases dynamically. This post has a solution that would solve the problem of passing the request.user or any other parameter by using a threading.local instance.
Someone created a reusable plugin even for this - https://github.com/ambitioninc/django-dynamic-db-router
Hope that helps.

Django foreign key constraint with Model that lives in different database

I'm trying to use the oauth2_provider library which provides a model for AccessToken, which foreign keys into a User model. My User model will actually live in a different database from the OAuth2 token models. I can use a router to direct which DB to use for a particular model, but am I correct in concluding that Django would not support a foreign key to a model in a different DB?
If I still wanted to extend from the AbstractAccessToken with my User in a different DB, is there any way that Django allows me to populate the user_id foreign key column at all? Or would I simply need to leave it null and define and have my custom AccessToken class define its own unconstrained external_user_id column?
Django doesn't support any ForeignKey operations that span multiple databases. So, as you suggested, I think the best you can do is to provide your own IntegerField for the user and use it manually. Unfortunately that may require a lot of fiddling with that third-party library if it has a lot of internal code that's expecting to pull the user from the database.

Django app has multiple database and multiple user

I have written one Django cloud based app. This app will have multiple user and for them multiple database, so that their data should be separate and they can save only to same database.
1) How can we implement it
2) How to automatically one user from login page to assign the database to write on it.
I don't have a complete answer, since you do not give a lot of detail. But here are a couple ots that f hinDjango supports custom database router implementations. A database router is a class that helps django decide which database to use for a particular model. Unfortunately I don't think this mechanism is granular enough for your needs. You can also specify the database to use in your code by using using(name) queryset method and save(using=name) form of save() method for instances. Of course this also means that some features of Django are going to be unvailable to you, since you cannot always expect to have a user. Look at the docs here for more info
https://docs.djangoproject.com/en/dev/topics/db/multi-db/

How do I take user input and then sum/add to the database in django

I am trying to get the user input and add to the database.
Example:
A user is going to type an integer, then this is to be added to the current value in the database. It's like sending money to someone via online banking.
Assuming you want to use Django's ORM, you will need to define a model. In your model you will have fields that define the data items to store. After you've had Django's manage.py tool setup the database, you can create instances of your model saving them with the save method of your model instance.
This probably seems like a lot of hand waving, and it is. What you should do is work through the Django tutorial as it will answer your questions. The tutorial is at the Django documentation site.

Django Mongodb Engine : Authentication, Sessions ans User Model

I'm new to Django and Mongodb seems really cool and I have a few
questions ! I'm using Django nonrel with Django Mongodb Engine.
I hope I'll not make too many mistakes :)
1 ) Are the Django user authentication system and the Django Session
system working fine ? Because I see on allbuttonspressed.com that
there is a problem with authentication and admin interface and the
part with the 3rd party written authentication backend makes me think
that the django authentication system doesn't work with mongodb :
You can only edit users in the admin interface if you add
"djangotoolbox" to your INSTALLED_APPS. Otherwise you'll get an
exception about an unsupported query which requires JOINs.
Florian Hahn has also written an authentication backend which provides
permission support on non-relational backends. You should use that
backend if you want to use Django's permission system.
2) If the authentication system works fine, how can I add fields to
the user model ? I saw on the Django docs that to achieve that the way
to go is to define a model with a OnetoOnefield to the user model
( "user = models.OneToOneField(User)" ) and define the other fields we
want in that model. I get it that must be the right way with SQL
databases. But with NoSQL like mongodb that just seem wrong to me, if
I'm not mistaken it creates a new collection and puts in each document
an user field used to link the document to the document in the User
collection ( exactly like a foreign key ). That doesn't seem to be a
NoSQL way at all ( Well It's just my feeling but since I'm just a
beginner I may be wrong, don't hesitate to correct me ). Is there a
recommended way to add fields directly to the User model ?
3) When the Model is used in Django, it puts all the fields in the
document even if they are empty right ? Isn't that a waste of space to
write down a lot of fields names in documents if they are empty ?
4) This question is more about Mongodb itself than the engine but I'll
ask it anyway, you may have the answer : How much extra space does it
take to index a field in a collection ?
Didn't think I would have written so much, I hope some of you had the
courage to read me !
Thanks in advance,
Nolhian
Only a partial answer as I don't use MongoDB.
I'm using django-nonrel in a Google AppEngine project. I'm using those other custom apps like "djangotoolbox", and some backends for GAE. Admin panel and standard Django authentication are working very well. I suspect it's the same for MongoDB (like mentioned in the quotation you have provided)
You're right. The standard approach is definitely good for relational databases, but might not work or work inefficiently for NoSQL databases. The typical scenario is to duplicate the data to another table, so you don't have to do JOINs. I think you can simply subclass the User model and add your fields to your custom model (docs).