Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
dango-reversion create new version of model instance when related model instance is changed
After spending plenty a lot of time, looking for the proper solution I think I need a help from someone who had more experience with django-reversion. Please, consider the situation I faced with. For example, I have next models: class Board(models.Model): ...some_fields class Topic(models.Model): board = models.ForeignKey(Board, related_name='topics') ...some_fields class Post(models.Model): topic = models.ForeignKey(Topic, related_name='posts') ...some_fields The behavior I expect to get is to create a new version of the Board instance when related topics or posts are changed. I can achieve this by registering models in the next order: reversion.register(Board) reversion.register(Topic, follow=['board',]) reversion.register(Post, follow=['topic',]) But in such case createinitialrevisions command creates as many initial versions for the Board instances as there are Topic and Post objects related to the certain Board, I don`t need this. To be more clear, please take a look at django-shell output: >>> from boards.models import Board, Topic, Post >>> from reversion.models import Version >>> board = Board.objects.get(id=1) >>> board.topics.count() 52 >>> board.get_posts_count() 5004 >>> versions = Version.objects.get_for_object(board) >>> len(versions) 5057 Here is the django-admin with board`s history: Thanks for any help in advance! -
Does django cassandra engine allows to query on multiple keyspaces of same cluster
I have multiple keyspaces in cassandra database each having few tables. I have done cassandra connection from settings.py . But don't know how to change the keyspace name for some query in django orm. -
Apache + Django + WSGI : Page is not working
i don't understand why my apache server doesn't work. When i try to connect to the address http://bde.yggdrasil.cafe with opera i have the following message This page isn't working bde.yggdrasil.cafe is currently unable to handle this request. i i don't undrstand why. I enables mod_wsgi in /etc/httpd/conf/http.conf Here is the config file I import in my main config : $ cat /etc/httpd/conf/extra/bdeweb.conf <VirtualHost *:80> # This is name based virtual hosting. So place an appropriate server name # here. Example: django.devsrv.local ServerName bde.yggdrasil.cafe ServerAdmin thibaut.cens@epita.fr DocumentRoot /srv/http/bdeweb # This alias makes serving static files possible. # Please note, that this is geared to our settings/common.py # In production environment, you will propably adjust this! Alias /static/ /hdd/bdeweb/static # This alias makes serving media files possible. # Please note, that this is geared to our settings/common.py # In production environment, you will propably adjust this! Alias /media/ /srv/http/bdeweb/media # Insert the full path to the wsgi.py-file here WSGIScriptAlias / /srv/http/bdeweb/bdewebsite/wsgi.py # PROCESS_NAME specifies a distinct name of this process # see: https://code.google.com/p/modwsgi/wiki/ConfigurationDirectives#WSGIDaemonProcess # PATH/TO/PROJECT_ROOT is the full path to your project's root directory, # containing your project files # PATH/TO/VIRTUALENV/ROOT: If you are using a virtualenv specify the full # path … -
Django - must be str, not int
I get an interesting exception. If I have my code like this: {% if page_nr != 0 %} <a href="{% url 'post:detail' topic.id page_nr|increase:-1 %}">Previous Page</a> {% endif %} {%page_not_over_amount page_nr amount_comments limit_amount_comment%} {% if comment_not_over_amount %} <a href="{% url 'post:detail' topic.id page_nr|increase:1 %}">Next Page</a> {% endif %} I will get an exception: Error during template rendering In template C:\Users\Nutzer\PycharmProjects\selfTry\post\templates\post\comment_block.html, error at line must be str, not int line 22 is <a href="{% url 'post:detail' topic.id page_nr|increase:-1 %}">Previous Page</a> However, if I remove my custom tag, make my code looks like : {% if page_nr != 0 %} <a href="{% url 'post:detail' topic.id page_nr|increase:-1 %}">Previous Page</a> {% endif %} {% if comment_not_over_amount %} <a href="{% url 'post:detail' topic.id page_nr|increase:1 %}">Next Page</a> {% endif %} the exception is gone! This is my custom tag: @register.inclusion_tag('post/comment_block.html') def page_not_over_amount(page_nr, comment_amount, comment_limit): result = page_nr * comment_limit < comment_amount - comment_limit return {'comment_not_over_amount': result} Here is all the traceback: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/post/1/0/ Django Version: 1.11.3 Python Version: 3.6.2 Installed Applications: ['post.apps.PostConfig', 'music.apps.MusicConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template error: In template C:\Users\Nutzer\PycharmProjects\selfTry\post\templates\post\comment_block.html, error at line 22 must be str, not … -
Django-CMS admin tool Template
I have created html template named testTemplate which is added to CMS_TEMPLATES: CMS_TEMPLATES = ( ## Customize this ('fullwidth.html', 'Fullwidth'), ('sidebar_left.html', 'Sidebar Left'), ('sidebar_right.html', 'Sidebar Right'), ('testTemplate.html', 'testTemplate') ) Then in fullwidth.html file I have changed the {% extends "base.html" %} to {% extends "testTemplate.html" %}. In testTemplate.html file I can find few {% placehoders %}. And now if I want to go to django-cms to add a content to placeholders, my cms-admin does not look right. Layout of cms admin looks like the template elements. How to separate the cms-admin template and my site template to make it work correctly? -
Reverse for 'password_reset_done' not found. 'password_reset_done' is not a valid view function or pattern name
I have a problem with django's view "password_reset_done". When I try to open accounts/reset-password I have this error. But if I open url accounts/reset-password/done it works. URLS.PY of "accounts" app from django.conf.urls import url from django.contrib.auth.views import login , logout, password_reset, password_reset_done from . import views urlpatterns = [ url(r'^register/$', views.register, name='register'), url(r'^profile/$', views.profile, name='profile'), url(r'^profile/prpage/(\d+)/$', views.profile, name='prpage'), url(r'^profile-edit/$', views.profiledit, name='profile-edit'), url(r'^login/$', login ,{'template_name':'accounts/login.html'}, name='login'), url(r'^logout/$', views.logout_view, name='logout'), url(r'^profile/(?P<proj_id>\d+)/$', views.userprojectpage, name='userprojectpage'), url(r'^changepassword/$', views.changepassword, name='changepassword'), url(r'^reset-password/$', password_reset, name='reset_password'), url(r'^reset-password/done/$', password_reset_done, name='password_reset_done'), ] please help! Thanks in advance) -
How to get django template from django_pandas dataframe?
How do you get django templates from a django_pandas dataframe? Documentation with django and pandas focuses on models. It does not trace the coding process from model to view to template. Using the example here: https://github.com/chrisdev/django-pandas#dataframemanager it is possible to translate a django model to a pandas dataframe. # models.py from django.db import models from django_pandas.managers import DataFrameManager class MyModel(models.Model): full_name=models.CharField(max_length=25) age = models.IntegerField() department = models.CharField(max_length=3) wage = models.FloatField() objects = DataFrameManager() def __str__(self): return self.full_name Subsequently, you can manipulate the dataframe, for example, reseting the index. Q1: How should you use views.py to get that dataframe to a template? you might transform it using df.to_html() as per below, or use df.to_json(), but I'm expecting because its Django that there is a best practice to place the df into a template. # views.py - here spits out html string, do I just resort to ElementTree? from django.shortcuts import render from django_pandas.io import read_frame from .models import MyModel def LookatMyModel(request): queryset = MyModel.objects.all() template_name = 'pandatest/page1.html' df = queryset.to_dataframe() #df = df.set_index('full_name') # effectively we can change the model. print (df.head()) df1 = df.to_html() context = { 'object_list': df1} print(df1) return render (request, template_name, context,) # templates/page1.html {% block content … -
Django autocomplete light: no input field
I've installed "Django autocomplete light" and now following this tutorial: http://django-autocomplete-light.readthedocs.io/en/master/tutorial.html Here is my code so far: setting.py INSTALLED_APPS = [ 'dal', 'dal_select2', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.gis', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'accounts', 'directory', 'geopy', ] models.py class Company(models.Model): CATEGORY_CHOICES = ( ('P', 'Parrucchiere'), ('Ce', 'Centro estetico'), ) self_key = models.ForeignKey('self', null=True, blank=True, related_name='related_self_key_models') city = models.ForeignKey(City, on_delete=models.CASCADE) name = models.CharField(max_length=200) address = models.CharField(max_length=255) telephone = models.CharField(max_length=200) category = models.CharField(max_length=1, choices=CATEGORY_CHOICES, null=True) email = models.CharField(max_length=255, null=True, blank=True) vat = models.CharField(max_length=200, null=True, blank=True) location = gis_models.PointField(u"longitude/latitude", geography=True, blank=True, null=True) gis = gis_models.GeoManager() objects = models.Manager() slug = AutoSlugField(populate_from='name', null=True) def __str__(self): return self.name views.py class CompanyAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): # Don't forget to filter out results depending on the visitor ! if not self.request.user.is_authenticated(): return Company.objects.none() qs = Company.objects.all() if self.q: qs = qs.filter(name__istartswith=self.q) return qs forms.py class AddCompanyForm(forms.ModelForm): vat = forms.CharField(required=True) class Meta: model = Company fields = ('name','city','address','telephone','email','vat','self_key') widgets = { 'self_key': autocomplete.ModelSelect2(url='company-autocomplete') } def clean_vat(self): vat = self.cleaned_data['vat'] if Company.objects.filter(vat__iexact=vat).count() > 1: raise ValidationError("L'attività digitata esiste già...") return vat urls.py url( r'^company-autocomplete/$', autocomplete.Select2QuerySetView.as_view(model=Company), name='company-autocomplete' ), html {% extends 'base.html' %} {% load static %} {% block title %} <title>Aggiungi azienda | ebrand directory</title> {% endblock title %} {% block upper_content %} … -
Django migrate command fails (duplicate key value) after a Heroku deployment
The migration made no problem in local environment. I'm using a "release phase" in my Heroku deployment, with the migrate command. The error: django.db.utils.IntegrityError: duplicate key value violates unique constraint "django_content_type_pkey" DETAIL: Key (id)=(1) already exists. Here is the full traceback from heroku release logs: Operations to perform: Apply all migrations: admin, animation, api_hooks, auth, authtoken, contenttypes, feedback, profiles, sessions Running migrations: Applying animation.0001_initial... OK Applying feedback.0003_customerexperiencefeedback_kind... OK Applying profiles.0002_teammember... OK Applying profiles.0003_customer_balance_alert_threshold... OK Traceback (most recent call last): File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/contenttypes/models.py", line 54, in get_for_model ct = self.get(app_label=opts.app_label, model=opts.model_name) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/query.py", line 380, in get self.model._meta.object_name __fake__.DoesNotExist: ContentType matching query does not exist. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/query.py", line 464, in get_or_create return self.get(**lookup), False File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/query.py", line 380, in get self.model._meta.object_name __fake__.DoesNotExist: ContentType matching query does not exist. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 65, in execute return self.cursor.execute(sql, params) psycopg2.IntegrityError: duplicate key value violates unique constraint "django_content_type_pkey" DETAIL: Key (id)=(1) already exists. The above exception was the direct cause of the following exception: Traceback (most recent … -
NOT NULL constraint failed: music_song.album_id
I am using django 1.11.6 and python 3.6.2 I'm new to django and there is no one to help me where i live so you guys are all my hope in my django application in the add song section i faced an error error message = IntegrityError at /music/album/5/AddSong/ NOT NULL constraint failed: music_song.album_id here is my views file: from django.views import generic from django.views.generic import View from .forms import UserForm from django.views.generic.edit import CreateView,UpdateView,DeleteView from django.shortcuts import render,redirect from django.contrib.auth import authenticate, login from .models import Album, Song from django.core.urlresolvers import reverse_lazy class IndexView(generic.ListView): template_name = 'music/index.html' context_object_name = 'all_albums' def get_queryset(self): return Album.objects.all() class DetailView(generic.DetailView): model = Album template_name = 'music/detail.html' context_object_name = 'album' class AlbumCreate(CreateView): model = Album fields = ['artist', 'album_title', 'genre', 'album_logo'] class SongCreate(CreateView): model = Song fields = ['song_title', 'file_type'] class AlbumUpdate(UpdateView): model = Album fields = ['artist', 'album_title', 'genre', 'album_logo'] class AlbumDelete(DeleteView): model = Album success_url = reverse_lazy('music:index') class UserFormView(View): form_class = UserForm template_name = 'music/registration_form.html' #display a blank form def get(self,request): form = self.form_class(None) return render(request,self.template_name, {"form": form}) #procces form data def post(self,request): form = self.form_class(request.POST) if form.is_valid(): user = form.save(commit=False) #cleaned (normalized) data username = form.cleaned_data['username'] password = form.cleaned_data['password'] user.set_password(password) user.save() … -
Log out every logged in user in django
I have one situation in which if admin performs any particular action I need to log user out. I know one that is remove authentication token from the database. is there any other way to do it? thank you in advance. -
Django - Enter a list of values - ManytoManyField
I made the supplier field a select dropdown box since I want it to behave that way but it produces an error: Enter a list of values my model class Product(models.Model): name = models.Charfield(max_length=250) supplier = models.ManytoManyField(Supplier) my form: class ProductForm(forms.ModelForm): class Meta: model = Product fields = ['name', 'supplier'] widgets = { 'supplier': forms.Select() } def clean_supplier(self): return [self.cleaned_data['supplier']]] It displays the error: Enter a list of values -
Django : Retrieve objects from relation
I am new in Django (1.11 used) and I read this (https://docs.djangoproject.com/fr/1.11/topics/db/models/) but I didn't find a clear answer for my question : How to retrieve the objets With an example , Suppose I have the following models : class StudentCollaborator(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) code_postal = models.IntegerField() collaborative_tool = models.BooleanField(default=False) def get_skills(self): return SkillHistory.objects.filter(student=self.user, value="acquired").values_list('skill') The skill history : class SkillHistory(models.Model): """ The reason why a Skill is acquired or not, or not yet, when and by who/how """ skill = models.ForeignKey(Skill) """The Skill to validate""" student = models.ForeignKey('users.Student') """The Student concerned by this Skill""" datetime = models.DateTimeField(auto_now_add=True) """The date the Skill status was created""" value = models.CharField(max_length=255, choices=( ('unknown', 'Inconnu'), ('acquired', 'Acquise'), ('not acquired', 'None Acquise'), )) """The Skill status : unknown, acquired or not acquired""" content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() reason_object = GenericForeignKey('content_type', 'object_id') reason = models.CharField(max_length=255) """Why the Skill is validated or not""" by_who = models.ForeignKey(User) class Meta: ordering = ['datetime'] and finally the skill class : class Skill(models.Model): """[FR] Compétence A Skill can be evaluated through questions answered by a student. Thus, when evaluated, a Skill can be acquired by a student, or not. """ code = models.CharField(max_length=20, unique=True, db_index=True) """The Skill reference code""" … -
django 'str' object has no attribute '_meta'
Sorry for my english. I have some data form enother server, but i need output this data like json. if i print response it contains in console { 'responseStatus': { 'status': [], }, 'modelYear': [ 1981, 1982 ] } but, if i return this response like HttpResponse i have error AttributeError: 'str' object has no attribute '_meta' this my code: data = serializers.serialize('json', response, ensure_ascii=False) return HttpResponse(data, content_type="application/json") -
How to modify slice of queryset persistently without save
I'm transforming (highlighting query matches) of a content attribute for objects in a search result queryset. When transforming the attribute during enumeration over every object in the queryset the transformation persists, at least for the life of the queryset. For obvious reasons I'm not applying a save, because I only want the transformation to persist for the life of the queryset during the request. The problem arises when I try to optimize the enumeration to a slice of the queryset, then the transformation no longer (temporarily) persists. Is there way to have transformations persist for a slice too? Why are my transformations treated differently for a slice than the full queryset? A slice of a queryset is still a queryset, although it does not have equivalence to the original queryset, even if its a slice of the entire queryset. Using Django 1.11.4 and Python 3.6.3 -
in django ,define MiddlewareMixin class .super(MiddlewareMixin, self).__init__() ?
i see the django source code.but i can't understand the following code class MiddlewareMixin(object): def __init__(self, get_response=None): self.get_response = get_response super(MiddlewareMixin, self).__init__() def __call__(self, request): response = None if hasattr(self, 'process_request'): response = self.process_request(request) if not response: response = self.get_response(request) if hasattr(self, 'process_response'): response = self.process_response(request, response) return response in detail,i don't understand super(MiddlewareMixin, self).__init__() what is the effect of this code? who can explain for me? thakns very much! -
django model forms fields template dry
We have a django application with tons of forms with generic template for rendering all form fields. Here is an example of one such form template. {% for field in form %} {% include "templates/_pratial/_field.html %} {% endfor %} _field.html <div class="form-group"> {{ field }} </div> forms.py class MyForm(forms.ModelForm): class Meta: model = MyModel def __init__(self, *args, **kwargs): super(MyForm, self).__init__(*args, **kwargs) self.fields['myfield'].widget.attrs.update({'class' : 'form-control'}) Now we are updating our layout with new html , our form now should look like this <div class="form-group "> <label class="control-label" for="email"> {{ field.label }} </label> <div class="input-group"> <div class="input-group-addon"> <i class="{{ field.?? }}"></i> //fa fa-envelope-o </div> {{ field }} </div> </div> How can i dynamically insert fa fa-envelope-o, without breaking dry Some thing like self.fields['myfield'].icon = "fa fa-envelope-o" in form init and can be easily used in template like {{ field.icon }} -
Django multiple dynamic databases after server startup
I'm new to django and try to figure out what would be the best solution for me to use dynamically multiple databases in django. I know django is able to work with multiple databases registered in the settings.py file but In my case I have one main database (sqlite) which acts as my repository, I created all the models, the rest api viewsets for this one. The user can choose to connect to a database by entering the connection information and then I will need to gather data from this database and insert it to my repository. The user can register multiple databases through the app. How can django work with those dynamic databases? Should I register them in the settings.py? Each view in the frontend maps to a specific database and I will need to switch context between them. Any help or insight would be appreciated, I didn't find anything matching my use case on the internet. -
plain text code parameters VS environment variables for web applications?
When we define settings for web applications, we face the choice to use plain text information on code or to request environment variable. Examples : (Stripe_KEY, Database name, Database password, ALLOWED_HOSTS for CORS, etc.) Concrete example on django : ALLOWED_HOSTS = [os.getenv('ALLOWED_HOSTS', '*')] VS ALLOWED_HOSTS = ['localhost:8000'] -
Django pass variable to URL tag
I am using Django 1.11. I am trying to add a link to a DeleteView template from the UpdateView. There is probably a better way to acheive this than the way I am attempting but I am new to Django and so the way i'm trying is to use a URL to direct to myapp/<pk>/delete/ In my template I have {% url 'calendar_delete' pk=event_id %} In my model I have class Event(models.Model): event_id = models.AutoField(primary_key=True) In my URLs I have url(r'^calendar/(?P<pk>\d+)/delete/$',views.CalendarDelete.as_view(),name='calendar_delete'), With the code as above the template doesnt render due to NoReverseMatch exception. '{'pk': ''}' not found, so its obviously not picking up the event_id from the model. When I hardcode a number in there it will render and the URL will direct me to the DeleteView template. Can anyone advise how I can get the <pk>/event_id into the URL tag? The <pk> exists in the URL of the UpdateView template and I have also tried to extract it from the URL as a variable and pass to the URL tag. I can extract ok but not pass in the variable. Any help on this would be much appreciated, including advice on better methods to use for the desired … -
Elastic search TransportError(400, 'search_phase_execution_exception', 'No mapping found
I am working with elasticsearch-dsl-py and django, and trying to implement the sorting mechanism in Text() field. The query for elastic search is s = Search(using=client, index="pustakalaya", doc_type=DocumentDoc).query("match_all").sort( 'title.keyword', ) # This is throwing error. as shown below. response = s.execute() Even though there is a title field which is a Text() type. I don't know why this is throwing error. If I remove keyword from title.keyword the error will be. TransportError(400, 'search_phase_execution_exception', 'Fielddata is disabled on text fields by default. Set fielddata=true on [title] in order to load fielddata in memory by uninverting the inverted index. Note that this can however use significant memory. Alternatively use a keyword field instead.') My mapping in elastic search is { "_index" : "index", "_type" : "document", "_id" : "b7f029bf-196c-4819-a17f-c2bd424710d8", "_score" : 1.0, "_source" : { "keywords" : [ "science fiction" ], "communities" : [ "literatures and arts" ], "author_list" : [ null ], "publication_year" : "2017-10-30", "year_of_available" : "2017-10-30", "collections" : [ "English Literature" ], "thumbnail" : "uploads/thumbnails/document/2017/10/30/thumb.png", "license_type" : "copyright retained", "created_date" : "2017-10-30T04:56:09.122064+00:00", "abstract" : "as k", "type" : "document", "publisher" : "Shree ram publication", "document_type" : "book", "updated_date" : "2017-10-30T05:02:09.720040+00:00", "document_interactivity" : "yes", "title" : "Mero kabita", "document_total_page" : … -
how to set Session time out in django 1.11
I am trying to set session time_out for admin in my django==1.11 . but it did not work with any of the following i tried please help me for better solution thanks in advanced other then this option if any solution is welcome. SESSION_EXPIRE_AT_BROWSER_CLOSE= True SESSION_COOKIE_AGE = 10 SESSION_IDLE_TIMEOUT = 10 SESSION_SAVE_EVERY_REQUEST = True SESSION_INACTIVITY_TIMEOUT_IN_SECONDS = 10 AUTO_LOGOUT_DELAY = 10 -
Virtual Environment installation Error
When I try to install a virtual environment in my local system. I'm getting this error.Could you please help me out to fix this issue $ pip -V pip 9.0.1 from /home/sysadmin/.local/lib/python2.7/site-packages (python 2.7) $ sudo pip install virutalenv sudo: unable to resolve host sysadmin-Veriton-M200-H61 The directory '/home/sysadmin/.cache/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag. The directory '/home/sysadmin/.cache/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag. Collecting virutalenv Could not find a version that satisfies the requirement virutalenv (from versions: ) No matching distribution found for virutalenv -
DRF - Set max and min value of a Serializer field
I've a serializer where I need to set the min and max value. Currently, this is how I do. class ProductSerializer(serializers.ModelSerializer): class Meta: model = Products extra_kwargs = { 'amount': {'min_value': 10000, 'max_value': 60000}, } This works fine, but I don't want to hardcode it, ie I want to fetch it from the DB, just in case the value changes. I've 2 models. 1) Category which has min & max value in it. 2) Products which has amount and category as a FK. The amount entered should be within the range of min-max. How can this be achieved? For eg:- Anything of this sort. extra_kwargs = { 'amount': {'min_value': Category.min, 'max_value': Category.max}, } -
Django compare queryset from different databases
I need to compare 2 querysets from the same model from 2 different databases. I switched db's on the fly, make 2 querysets and try to compare them (filter, or exclude) # copy connections connections.databases['tmp1'] = connections.databases['ukm'] connections.databases['tmp2'] = connections.databases['ukm'] # get dbs from form db1 = DB.objects.get(pk=form.cleaned_data['db1'].id) db2 = DB.objects.get(pk=form.cleaned_data['db2'].id) # left connection connections.databases['tmp1']['HOST'] = db1.host connections.databases['tmp1']['NAME'] = db1.name articles1 = list(Smdocuments.objects.using('tmp1').only('id').filter(doctype__exact='CQ')) # right connection connections.databases['tmp2']['HOST'] = db2.host connections.databases['tmp2']['NAME'] = db2.name articles2 = list(Smdocuments.objects.using('tmp2').only('id').filter(doctype__exact='CQ')) # okay to chain Smdocuments objects all = list(chain(articles1, articles2)) # not okay to diff sets of objects diff_set = set(articles1) - set(articles2) # not okay to exclude sets from different db articles_exclude = Smdocuments.objects.using('tmp1').only('id').filter(doctype__exact='CQ') len(articles1) diff_ex = Smdocuments.objects.using('tmp2').only('id').filter(doctype__exact='CQ').exclude(id__in=articles_exclude) len(diff4) So, "Model objects" not so easy to manipulate, and querysets between difference databases as well. I see, thats not a good db scheme, but it's another application with distributed db, and I need to compare them. It's would be enough to compare by one column, but probably compare full queryset will work for future. Or, should I convert queryset to list and compare raw data?