Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Could not resolve URL for hyperlinked relationship using view name "Settings Detail"
I have spent hours trying to debug the issue. I have not been able to understand how to set up HyperlinkedModelSerializer. Could you please point me to what I am doing wrong? Also, is there any good tutorial on understand Hyperlinked Relationships better besides official docs? Thanks! Error ImproperlyConfigured at /settings/ Could not resolve URL for hyperlinked relationship using view name "Settings Detail". You may have failed to include the related model in your API, or incorrectly configured the lookup_field attribute on this field. ..... During handling of the above exception (Reverse for 'Settings Detail' with keyword arguments '{'settings_id': UUID('24aee4eb-8f71-4336-8c36-a96c9e4447c9')}' not found. 1 pattern(s) tried: ['settings//$']), another exception occurred: models.py class Settings(models.Model): # General id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) createdAt = models.DateTimeField(auto_now_add=True) updatedAt = models.DateTimeField(auto_now=True) # Token publicToken = models.CharField(max_length=100) secretToken = models.CharField(max_length=100) serializers.py class SettingsListSerializer(serializers.HyperlinkedModelSerializer): url = serializers.HyperlinkedIdentityField( view_name = "Settings Detail", lookup_field='id', lookup_url_kwarg='settings_id' ) class Meta: model = Settings exclude = ('id', 'createdAt', 'updatedAt',) class SettingsDetailSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Settings exclude = ('id','createdAt', 'updatedAt',) urls.py from django.conf.urls import url from app import views urlpatterns = [ url(r'^$', views.HomeView.as_view(), name=views.HomeView.name), url(r'^settings/$', views.SettingsListView.as_view(), name=views.SettingsListView.name), url(r'^settings/<uuid:settings_id>/$', views.SettingsDetailView.as_view(), name=views.SettingsDetailView.name), ] views.py class SettingsListView(generics.ListCreateAPIView): queryset = Settings.objects.all() serializer_class = SettingsListSerializer permission_classes = … -
Django rest framework, double nested writable serializers
I have three models, each of which are related. A project has multiple phases, and a phase has multiple features: class Project(models.Model): # client = models.CharField(max_length=300) name = models.CharField(max_length=140) description = models.CharField(max_length=500) sold = models.BooleanField(default=False) class Phase(models.Model): name = models.CharField(max_length=140) sold = models.BooleanField(default=False) project = models.ForeignKey( Project, on_delete=models.CASCADE, related_name="phases" ) hourly_rate = models.IntegerField() class Feature(models.Model): phase = models.ForeignKey(Phase, on_delete=models.CASCADE, related_name="features") name = models.CharField(max_length=140) description = models.CharField(max_length=500) hours = models.IntegerField() According to the DRF docs, I have tried to write nested model serializers, based on this: ---------FROM DOCUMENTATION----------- class TrackSerializer(serializers.ModelSerializer): class Meta: model = Track fields = ('order', 'title', 'duration') class AlbumSerializer(serializers.ModelSerializer): tracks = TrackSerializer(many=True) class Meta: model = Album fields = ('album_name', 'artist', 'tracks') def create(self, validated_data): tracks_data = validated_data.pop('tracks') album = Album.objects.create(**validated_data) for track_data in tracks_data: Track.objects.create(album=album, **track_data) return album ----------END DOCUMENTATION----------- I have come up with this: class FeatureSerializer(serializers.ModelSerializer): class Meta: model = Feature exclude = ["phase"] class PhaseSerializer(serializers.ModelSerializer): features = FeatureSerializer(many=True) class Meta: model = Phase exclude = ["project"] def create(self, validated_data): features_data = validated_data.pop("features") phase = Phase.objects.create(**validated_data) for feature_data in features_data: Feature.objects.create(phase=phase, **feature_data) return phase class ProjectSerializer(serializers.ModelSerializer): phases = PhaseSerializer(many=True) class Meta: model = Project fields = "__all__" def create(self, validated_data): phases_data = validated_data.pop("phases") project = … -
how to add provided webpage in django
I want to add a web template I have made before to django template but it doesn't show like it original. for example I add https://github.com/ellisonleao/clumsy-bird project directly to my template/game and I render it : def Game(request): template = loader.get_template('game/index.html') return HttpResponse(template.render()) and none of css and js files included in index doesn't work -
how to format ckeditor in django UI
guys i am using ckeditor in my django project especially in django admin it works perfect in django admin. But when I go to templates i have this problem my code in base.html <div class="container"> <div class="row"> <div class="col-md-8"> {% block content %}{% endblock %} </div> </div> in post-detail.html {% block content %} {% for post in object_list %} <article class="media content-section"> <div class="media-body"> <div class="article-metadata"> <a class="mr-2" href="#">{{ post.author }}</a> <small class="text-muted">{{ post.post_date|date:"F d, Y" }}</small> </div> <h2><a class="article-title" href="{% url 'post-detail' post.id %}">{{ post.title }}</a></h2> <p class="article-content">{{ post.summary }}</p> </div> </article> {% endfor %} {% endblock %} how can i remove this overflow? or Am i missing to include something? -
Django UserCreationForm shows extra password fields
I'm using Django 2.1 and I've used UserCreationForm for a update form Like this: class UserUpdateForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username','email'] But when I use this form in template I see extra password fields and I don't want this two password fields and If it helps , I've used this class too as A register class class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username','email','password1','password2'] } -
Django Allow Interaction with Users Data Only
I'm adding some user profile behavior to a Django app, and as usual I would like to restrict users from only being able to interact with their own data. This SO Q&A is related to the process itself: Django--- Allowing Users to only edit their profile Is it enough to add the authenticated user id to the create, update, and delete queries? To reduce code duplication, I was thinking that I could write a mixin that would override get_object and intercept the query by adding the self.request.user.pk to filter the results? Are there other efficient methods for doing this, or mixins from Django itself? -
Django - Raw SQL Queries or Django QuerySet ORM
I know Django Object Relational Mapper (ORM) helps bridge the gap between the database and our code Performing raw queries. But I want to find out which is better - Raw SQL Queries or Django QuerySet ORM. So for that I was query on User Table - from django.contrib.auth.models import User Then i queried Django ORM QuerySet - orm_query = User.objects.all() orm_query <QuerySet [<User: superadmin>]> After QuerySet I user raw - raw_query = User.objects.raw("select * from auth_user") raw_query <RawQuerySet: select * from auth_user> And then I tried to print those queries using .query and it's output - print(orm_query.query) SELECT `auth_user`.`id`, `auth_user`.`password`, `auth_user`.`last_login`, `auth_user`.`is_superuser`, `auth_user`.`username`, `auth_user`.`first_name`, `auth_user`.`last_name`, `auth_user`.`email`, `auth_user`.`is_staff`, `auth_user`.`is_active`, `auth_user`.`date_joined` FROM `auth_user` print(raw_query.query) select * from auth_user And i found orm_query much longer than raw_query. I want to know which one is best raw or orm query. Which should i use for best performance. What is the difference between them. -
NoReverseMatch at / Reverse for 'category' with arguments '(u'Animals',)'
There are several similar issues, but I´m still no figuring out how to resolve fix my code. When I run the server Django gives me this error to me: > Reverse for 'category' with arguments '(u'Animals',)' and keyword > arguments '{}' not found. 0 pattern(s) tried: [] > Error during template rendering >In template /home/joelramone/django/myblog/blog/templates/pages/home.html, error at line 0 Here is urls.py from django.conf.urls import url from django.contrib import admin from django.conf import settings from django.views import static as django_static from blog import views as blog_views url(r'^admin/', admin.site.urls), url(r'^$', blog_views.home), url(r'^post/(?P<single>[-\w]+)/$', blog_views.single, name='single'), url(r'^category/(?P<category>[-\w]+)/$', blog_views.archive, name='category'), url(r'^images/(?P<path>.*)/$', django_static.serve, {'document_root': settings.BAS_DIR + '/images'}), Here is models.py class Post(models.Model): author = models.ForeignKey('auth.User') title = models.CharField(max_length=150) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) category = models.ManyToManyField('blog.Category', blank=True, null=True) image = models.FileField(blank=True, upload_to='images') def __str__(self): return self.title class Category(models.Model): title = models.CharField(max_length=150) slug = models.CharField(max_length=150) parent = models.ForeignKey('blog.Category', blank=True, null=True) @staticmethod def list_categories(): return Category.objects.all() def __str__(self): return self.title here is views.py def home(request): post_list = Post.objects.all() paginator = Paginator(post_list, 1) page = request.GET.get('page') categories = Category.list_categories() try: posts = paginator.page(page) except PageNotAnInteger: posts = paginator.page(1) except EmptyPage: posts = paginator.page(paginator.num_pages) d return render(request, 'pages/home.html', {'posts': posts, 'categories': categories}) def single(request, single): single = Post.objects.get(id=single) … -
Wagtail not shows ValidationError correctly
I have XOR validation of wagtail.core.models.Page descedant: def save(self, *args, **kwargs): if self.video_playlist is not None and self.gallery is not None: raise ValidationError(_("Only gallery or only video playlist must be filled")) elif self.video_playlist is None and self.gallery is None: raise ValidationError(_("Only gallery or only video playlist must be filled")) super(OkoPage, self).save(*args, **kwargs) But instead of red color highlighting wagtail returns 400 error. How to do it right? -
how to add custom send mail button in our default django admin
I am trying to send an email from django admin to the user who sends an email message from contact page.How can i do that ?? How can i add custom send reply button to the admin page so that the email can be send to the contact users email urls.py path('contact/',views.contact,name='contact'), path('contact/reply/',views.contact_reply,name='contact_reply'), models.py class Contact(models.Model): name = models.CharField(max_length=250) slug = AutoSlugField(populate_from='name') email = models.EmailField() subject = models.CharField(max_length=250) message = models.TextField() def __str__(self): return self.name class ContactReply(models.Model): email = models.ForeignKey(Contact, on_delete=CASCADE) slug = AutoSlugField(populate_from='email') subject = models.CharField(max_length=250) message = models.TextField() attachment = models.FileField(blank=True) def sendmail(self): email_list = [] for e in self.email: email_list.append(e.email) send_mail(str(self.subject), str(self.message),settings.EMAIL_HOST_USER, email_list,fail_silently=False) class Meta: verbose_name_plural = 'Reply To Contact' views.py def contact(request): if request.method == "POST": form = ContactForm(request.POST) if form.is_valid(): contact = form.save(commit=False) contact.save() messages.success(request,'Your message has been sent.') return redirect('rank:contact') else: messages.error(request,'Error in form.Try Again') return redirect('rank:contact') else: form = ContactForm() return render(request, "rank/contact.html",{'form':form}) def contact_reply(request): if request.method == "POST": form = ContactReplyForm(request.POST) if form.is_valid(): reply = form.save(commit=False) reply.save() messages.success(request,'Your message has been sent.') else: form = ContactForm() return render(request, "rank/reply_to_contact.html",{'form':form}) forms.py class ContactForm(forms.ModelForm): class Meta: model = Contact fields = ['name','email','subject','message'] class ContactReplyForm(forms.ModelForm): class Meta: model = ContactReply fields = ['email','subject','message','attachment'] admins.py admin.site.register(Contact) … -
how to create two records in two modes at a time one having foreign key
Assume i have two models. ModelA & ModelB.ModelB will have Foregin key to ModelA. i want to create each record in both tables one haveing foregin key. models.py Class ModalA(models.Model): name = models.CharField(max_length=200) location = models.CharField(max_length=200) Class ModelB(models.Model): modela = models.ForeignKey(ModalA,on_delete=models.CASCADE) state = models.CharField(max_length=200) country = models.CharField(max_length=200) serializer,py class ModelBSerializers(serializers.ModelSerializer): class Meta: model = ModelB fields = "__all__" class ModalASerializers(serializers.ModelSerializer): class Meta: model = ModalA fields = "__all__" def create(self, validated_data): return ModalA(**validated_data) I would like to know how to create bot records in tables. -
Which is the effective way to update Many to Many fields in serializers using Django Rest Framework
I have the following model and would like to create an update function in the serializers. class Employee(models.Model): """ Model, which holds general employment information of an employee in an organization. """ user = models.CharField(max_length=100, unique=True, blank=True, null=True) hr_number = models.CharField(verbose_name='HR number',blank=True, null=True,max_length=20, unique=True) department = models.ManyToManyField(Department) unit = models.ManyToManyField(Unit) So far this is my implementation of the update method. def update(self, instance, validated_data): department_data = validated_data.pop('department') unit_data = validated_data.pop('unit') instance.hr_number = validated_data.get( 'hr_number', instance.hr_number ) return instance -
i have created the update function but have no success it is saying dict object has no attribute 'data ' can anyone help to fix update function
basically i am trying to evalutionTest but i am not able to update it i thing there is something wrong with my code i am new to DRF is there some one who could help me out that will be help full * Serializer.py class EvaluationTestSerializer(serializers.ModelSerializer): questions = serializers.SerializerMethodField() admin = StringSerializer(many=False) category = StringSerializer(many=False) class Meta: model = EvaluationTest fields='__all__' def get_questions(self,obj): questions = QuestionSerializer(obj.questions.all(), many=True).data return questions This is where i want help to make it work i am not sure it is not properly can someone help me fixing this update function def update(self,instance,validated_data): # data = request.data # print(data) evaluationtest = EvaluationTest() # admin= User.objects.get(username=data['admin']) cat=Category.objects.get(id=validated_data['category']) # print(cat) evaluationtest.category=validated_data.get('category',evaluationtest.category) evaluationtest.admin = validated_data.get('admin',evaluationtest.admin) evaluationtest.title = validated_data.get['title',evaluationtest.title] evaluationtest.type = validated_data.get['type',evaluationtest.type] evaluationtest.save() order = 1 for q in validated_data['questions']: newQ = Question() newQ.question=q['title'] newQ.order = order newQ.save() for c in q['choices']: newC = Choice() newC.title = c newC.save() newQ.choices.add(newC) newQ.answer = Choice.objects.get(title=q['answer']) newQ.evaluationtest = evaluationtest newQ.save() order += 1 return evaluationtest -
How do I prevent a manager added in an abstract model from becoming the default?
We frequently add soft_deleted fields to our models in order to mark them as deleted without actually deleting them in case the user / we have made a mistake and we want to undo it, and for other record keeping reasons. I wanted to commonize this by adding an abstract model class with that field and a manager to get undeleted objects on it (and some other not-relevant-here methods): from django.db.models import Manager, Model class UndeletedObjectsManager(Manager): def get_queryset(self): return self.model._default_manager.filter(soft_deleted=False) class SoftDeletableModel(Model): class Meta: abstract = True soft_deleted = BooleanField(default=False) undeleted_objects = UndeletedObjectsManager() However, when I use it, depending I think on MRO order, sometimes the undeleted_objects manager ends up as the default manager, rather than objects which is defined on another abstract model class, meaning that e.g. reverse many-to-many managers don't work properly (they filter by soft_deleted). I know that I could set default_manager_name in the Meta class, but then I'd be forcing the default manager name for all model subclasses, which I don't want to do. Is there any other way I can prevent this from happening, and guarantee that undeleted_objects won't be picked as the default manager? -
Order a queryset by column of type datetime
I have a column "timestamp" in my model of type datetime. I would like to sort the queryset in descending order of timestamp. MyTable.objects.all().order_by('-timestamp') TypeError : argument must be int or float How to debug this issue? Thanks! PS : I am using DRF and I am unable to order it in my serializer or view (using django-filter) -
Get input value and display it in other template
sorry I just learned programming I have registration template and registration success template. after user fill the form registration, it will be redirect to registration success template How to get input value['email'] from registration template and display it in registration success template ? views.py class RegisterFormView(TemplateView): template_name = 'home/register.html' def get(self, request): user_form = UserForm() return self.render_to_response({ 'base_url' : settings.BASE_URL, 'user_form': user_form, }) def post(self, request, *args, **kwargs): if request.method == 'POST': user_form = UserForm(request.POST) if user_form.is_valid(): user = user_form.save() user.full_name = user_form.cleaned_data.get("full_name") user.email = user_form.cleaned_data.get("email") user.phone_number = user_form.cleaned_data.get("phone_number") user.set_password(user_form.cleaned_data.get("password")) password = user_form.cleaned_data.get("password") profile = Profile.objects.create(created_by=user) user.save() return redirect(reverse("home:register-success")) else: user_form = UserForm(request.POST) return self.render_to_response({ 'base_url' : settings.BASE_URL, 'user_form': user_form, }) register.html {{user_form|crispy}} register-success.html we have send email activation to {{user.email}} -
Django Crontab : How to stop parallel execution
I have few cronjobs running with the help of django-crontab. Let us take one cronjob as an example, suppose this job A is scheduled to run every two minutes. However, while the job is running and if it is not finished in two minutes, I do not want another instance of this job to execute. Exploring few resources, I came accross this article, but I am not sure where to fit this in. https://bencane.com/2015/09/22/preventing-duplicate-cron-job-executions/ Did someone already came accross this issue? How did you fix it? -
How could I make authentication in Django using Salt-API?
I just set up salt-api in my local machine and it is working fine. It can communicate with server. Now, I want to build up sample UI project using Django for knowing the status of server. Is there any simple way to integrate Django and salt-api? I have now authentication problem with Django using salt-api. Could anyone give me some clue to start my project. Thanks in advance. -
How to modify value of a django model object automatically when model item "edit/change" page is opened?
How to modify a value of a django model object automatically when model item "edit/change" page is opened/clicked and not saved is clicked.? Basically I need this to keep track of read and unread data items. Just like keeping track of email message read/unread. I know how to implement it when save button is clicked in django admin and I am currently doing it manually, but I want to automatically change a particular value just when change/edit link is clicked, so that I can keep track of newly created orders. As shown in the screenshots below I want the boolean value "read"[second image] to be changed automatically when "id 26" is clicked[first image] -
Django - Postgresql database restore - IntegrityError
I have same source code on my local machine and on server, I created new database on my PC and filled it with my data, then I dumped databse using 'pg_dump :database_name: > outfile' and restored it on brand new database on server, in during what I'm getting ERROR: relation "public.account_emailaddress_id_seq" does not exist LINIA 1: SELECT pg_catalog.setval('public.account_emailaddress_id_seq... Can someone explain to me why that happen, how to dump/restore database in the right way with django and postgresql and what could I do now for fix that? -
Apache 2 can't find python packages under Django project directory
I am running Apache2 and Django in a Ubuntu Docker container. Apache can find and is trying to run the Django project but cannot find the python packages contained in under the project directory. It is returning an Import error. See attached picture. Django error message ImportError at / Missing required dependencies ['numpy'] Request Method: GET Request URL: http://localhost:8005/ Django Version: 2.1.7 Exception Type: ImportError Exception Value: Missing required dependencies ['numpy'] Exception Location: /var/www/html/django_demo_app/INDmain/Lib/site-packages/pandas/__init__.py in <module>, line 19 Python Executable: /usr/bin/python3 Python Version: 3.6.7 Python Path: ['/var/www/html/django_demo_app/INDmain', '/var/www/html/django_demo_app/INDmain/Lib/site-packages', '/var/www/html/django_demo_app/INDmain/Scripts', '/usr/lib/python36.zip', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', '/usr/local/lib/python3.6/dist-packages', '/usr/lib/python3/dist-packages', '/var/www/html/django_demo_app/INDmain', '/var/www/html/django_demo_app/INDmain', '/var/www/html/django_demo_app/INDmain/main'] I had the same issue when Apache/Django tried to find the requests package under /var/www/html/django_demo_app/INDmain/main/Lib/site-packages so I added the directory to the path and Apache/Django found the package. Now it is finding the pandas package but cannot find the dependency numpy package located in the same directory. What could be causing Apache and/or Django to fail to see these packages? My configuration/settings files are below. Common settings are not shown for brevity. Apache .conf file WSGIPythonPath /var/www/html/django_demo_app/INDmain <VirtualHost *:80> # The ServerName directive sets the request scheme, hostname and port that # the server uses to identify itself. This is used when creating … -
Cannot auth ldap user by django-auth-ldap
I´m having problems getting ldap users authenticated with django-auth-ldap 1.2.8. I can log-in by use of Apache Directory Studio as followed: hostname: private.pai.org port: 389 Auth: Bind DN – cn=testuser1@test.com,ou=users,dc=ldap,dc=pai,dc=org` Bind Password: thePassword But when trying with Django with following settings: import ldap from django_auth_ldap.config import LDAPSearch,GroupOfUniqueNamesType # logging import logging logger = logging.getLogger('django_auth_ldap') logger.addHandler(logging.StreamHandler()) logger.setLevel(logging.DEBUG) # where to search AUTH_LDAP_SERVER_URI = "ldap://private.pai.org:389" AUTH_LDAP_USER_SEARCH = LDAPSearch("ou=users,dc=ldap,dc=pai,dc=org", ldap.SCOPE_SUBTREE, "(cn=%(user)s)" ) # group settings AUTH_LDAP_GROUP_SEARCH = LDAPSearch("dc=ldap,dc=pai,dc=org", ldap.SCOPE_SUBTREE, "(objectClass=GroupOfUniqueNames)" ) AUTH_LDAP_GROUP_TYPE = GroupOfUniqueNamesType() # disable caching AUTH_LDAP_GROUP_CACHE_TIMEOUT = 0 AUTH_LDAP_CACHE_GROUPS = 0 # bind user to django groups AUTH_LDAP_USER_FLAGS_BY_GROUP = { "is_active": ("ou=users,dc=ldap,dc=pai,dc=org" ), "is_staff": ("ou=users,dc=ldap,dc=pai,dc=org") } AUTH_LDAP_USER_ATTR_MAP = { "email": "cn" } I´m getting following error search_s('ou=users,dc=ldap,dc=pai,dc=org', 2, '(cn=testuser1@test.com)') raised NO_SUCH_OBJECT({'desc': u'No such object'},) This looks like the cn cannot be found in ou? Can somebody say how to overcome this error? -
Django Saving selected values of ManytoMany Field
Here I am trying to save selected fields in the manytomany field. When I try to save the selected fields all fields other than selected are also saved. How can i save only the selected fields. here is my model.. #model class Products(models.Model): name = models.CharField(max_length=128) product_code = models.CharField(max_length=128) cmp_id = models.ManyToManyField(Components, blank=True) bay_id = models.ManyToManyField(ScanningBay, blank=True) def __str__(self): return self.name #form class ProductForm(forms.ModelForm): name = forms.CharField(max_length=15,widget=forms.TextInput(attrs={'class':'form-control','placeholder': 'Product Name','size': '40'})) product_code = forms.CharField(max_length=15, widget=forms.TextInput( attrs={'class': 'form-control', 'placeholder': 'Product Code', 'size': '40'})) bay = forms.ModelMultipleChoiceField(queryset=ScanningBay.objects.all()) component = forms.ModelMultipleChoiceField(queryset=Components.objects.all()) class Meta: model = Products fields = ('name', 'product_code','bay','component')" #views def products(request): if request.method == 'POST': p_form = ProductForm(request.POST or None) new = p_form.save(commit=False) new.save() z = p_form.save_m2m() print (z) return HttpResponse("success") else: pdct_form = ProductForm() return render(request, 'app/products.html', {'pdct':pdct_form}) this is the template rendered <form id="test" class="impexform" action="{%url 'products'%}" method="POST"> {% csrf_token %}> {{pdct}} <button type="submit" class="btn btn-sm btn-danger mt-3" style="background:#ed2526; border-radius: 30px; width: 8rem;">Add Product</button> </form> -
Django OperationalError: no such table
I've ran all the commands under the sun to try and fix this which normally solve the problem but this time nothing is working. python manage.py makemigrations python manage.py migrate python manage.py migrate --run-syncdb python manage.py users --fake users python manage.py migrate users 0012 I've read a few questions on SO and now think it has to do with something executing immediately when imported so the migration doesn't go through. The only thing I've changed is added a new model TextSubmission and altered views.py. If someone could show me / identify the problematic code, I would greatly appreciate it. Running migrations: Rendering model states... DONE Unapplying users.0014_auto_20190314_1141...Traceback (most recent call last): File "/home/user/env/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "/home/user/env/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 298, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such table: users_textsubmission The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/home/user/env/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/user/env/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/user/env/lib/python3.6/site-packages/django/core/management/base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "/home/user/env/lib/python3.6/site-packages/django/core/management/base.py", line 353, in execute output = self.handle(*args, **options) File "/home/user/env/lib/python3.6/site-packages/django/core/management/base.py", line 83, in wrapped res = handle_func(*args, **kwargs) … -
Django ORM: Combine exlude with not in filter
For this (strongly simplified) Django model setup: class A(models.Model) class B(models.Model) a = models.ForeignKey(A, null=True, blank=True) class C(models.Model) b = models.ForeignKey(B, null=True, blank=True) I would like to make sure that for a query on C, no related objects that are not [a1,a2] are part of a query. Something like: qs = C.objects.exclude(b__a__NOT_in=[a1, a2]). What I'm searching for is not qs = C.objects.filter(b__a__in=[a1, a2]) as my foreign keys are nullable, and I would also like to fetch cases in which any of the fks on the way is null. What's the most elegant way to solve this ? Thank you!