Django model wih a ForeignKey pointing to a salesforce model - django

I am using django-salesforce and I would like to create a model within Django that has a ForeignKey field pointing to a SFDC model (hosted on force.com).
I created a custom model on force.com, let us call it SFModel, and I can successfully work on it from django (CRUD) by subclassing salesforce.models.Model.
I also created a django.db.models.Model, let us call it DJModel, that has a unique field ForeignKey(SFModel). This model is registered on the admin panel.
All models validate and I can go to my admin panel to try to create a new instance of DJModel. However, when I try to display the create_form in the admin I get the following error :
hasattr(): attribute name must be string
and the debug stream says
So I tried to set an arbitrary alias to the SF entry in the DATABASES of my settings.py. There is a dedicated variable for that :
SALESFORCE_DB_ALIAS = 'youralias'
But I still have the same problem.
Any recommendation?

Django doesn't support it and an external reference to Salesforce should be currently saved as a CharField and a reference to other databases as IntegerField.
Django docs about Limitations of multiple databases:
Django doesn’t currently provide any support for foreign key or many-to-many relationships spanning multiple databases. If you have used a router to partition models to different databases, any foreign key and many-to-many relationships defined by those models must be internal to a single database.
I tried the cross reference with sqlite as 'default' database. It was possible to create an object of model DJModel with cross-database reference from sqlite to Salesforce. It behaves similarly to normal Django cross-database references, without obscure errors and only a dot reference can be used.
EDIT: Simplified after many years.

Related

How can I implement authentication in Django

I am new to Django.
I am going to build simple register and login fullstack application by using React and Django.
My problem is when I received register request with form data.
Is it ok to create custom table for users?
I am going to create another table related to user table.
So in that case, there must be id in the users.
That's why I am going to create custom table.
Please help me it is good practice.
You can abstract from AbstractBaseUser and then you can customise the user model and to specify it in your settings file.
Please see the django documentation here:
https://docs.djangoproject.com/en/4.1/topics/auth/customizing/#substituting-a-custom-user-model
In Django you can link between multiple table by different relationships depends on what you want like:
OneToOne
ForeignKey
ManyToMany
And by default when you create a model django create a pk field it is ID for table, you can make another field as a primary key for model
When you use one of those relationships django by default use model id to link between them
and you can also create a custom user model to use it
Good luck

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.

Maintain two different model schema version to connect two different database in Django

In my Django app, I have one model Question which is connected to database db_one.
Now I want add and modify few fields in Question model. Until the new Question model schema is tested thoroughly, I want to keep the old Question model schema accessible in UI. Also I am maintaining a separate database db_two for this new schema such that main app is not affected.
How can model schema versioning be achieved in Django such that I could select the database based on model version?
Or, Is there any better approach to deal with this?

Connecting and importing models from multiple database connections Django

In a django app, I have two postgresql databases connected through settings.py: one is default and other is AppDb. AppDb is placed on a remote machine.
I want to query from a 'Courses' model from AppDb using 'using()' and 'Courses' model is not available in default database.
So my query goes like this:
courseInfo = Courses.objects.using('AppDb').filter(cuser_id = 12)
But I am getting NameError for 'Courses'
Can I have a solution for such queries without using routers
If you have an existing database, you still need to create an app and models for that database in order to use the ORM.
To help you create the model classes, you can use the inspectdb management command which will try to guess the models from an existing database and create the models.py for you. Its not perfect, but it will save you some time.
You will still have to make sure the models have a primary key and are written in the correct order (so that foreign keys will work correctly).