Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Got AttributeError when attempting to get a value for field
**While attemping to create two objects (without nested serializer)from one end point. i got an error ERROR: AttributeError at /migratestudent Got AttributeError when attempting to get a value for field registration_no on serializer StudentDataMigrateSerializer. The serializer field might be named incorrectly and not match any attribute or key on the Student instance. Original exception text was: 'Student' object has no attribute 'registration_no'. class Student(models.Model): name = models.CharField(max_length=300) sex = models.CharField(choices=SEX_CHOICES,max_length=255, null=True) Category = models.CharField(max_length=100, null=True) def __str__(self): return self.name class Registration(models.Model): registration_no = models.CharField(max_length=255, unique=True) student = models.OneToOneField(Student, on_delete= models.CASCADE, related_name='registration') def __str__(self): return self.registration_no class StudentDataMigrateSerializer(serializers.Serializer): name = serializers.CharField() sex = serializers.CharField() registration_no = serializers.CharField() #registration_no = serializers.CharField() def create(self,validated_data): name = validated_data.pop('name') sex = validated_data.pop('sex') registration_no= validated_data.pop('registration_no') #registration_no = validated_data.pop('registration_no') #check for existence of registration number #Student.objects.CheckRegistration(name, '4') try: regn = Registration.objects.get('registration_no') except: student = Student.objects.create(name=name, sex=sex) registration = Registration.objects.create( registration_no=registration_no, student=student) return student class StudentDataMigrateCreateAPIVIew(ListCreateAPIView): serializer_class= StudentDataMigrateSerializer def get_queryset(self): student = Student.objects.all() return student -
How can I send e-mail to my e-mail address from the web site I prepared in django html?
I want to send my visitors' names, e-mails, topics and messages to my e-mail address via the website I prepared with Django. mysite/views.py def contact(request): if request.method == 'GET': form = ContactForm() else: form = ContactForm(request.POST) if form.is_valid(): subject = form.cleaned_data['subject'] from_email = form.cleaned_data['from_email'] message = form.cleaned_data['message'] try: send_mail(subject, message, from_email, ['my@mail.com']) except BadHeaderError: return HttpResponse('Invalid header found.') return HttpResponse('Thanks for your email') return render(request,'giris/contact.html',{'form': form}) {% block content %} {% load widget_tweaks %} Contact Us {% csrf_token %} {{ form.as_p }} {% endblock %} I want to display and e-mail the template I prepared with django-widget-tweaks. -
Expiring a Django session at a specific time for a specific user (eg when their shift ends) at login
I have a system that has overlapping shift workers on it 24/7. Currently it is not uncommon for one to forget to log out and the next worker pick up their session and run with it. This causes some accountability issues. I do realise there are options for session length ie settings.SESSION_COOKIE_AGE but these are a bit blunt for our purposes. We have different workers with different shift lengths, managers who have 2FA on-action and it's basically just not the path we want to pursue. Simply put... I want to programmatically set the session death time on login. We already have a custom Login view but this bubbles up through the built-in django.contrib.auth.forms.AuthenticationForm. And even there I can't see how to set an expiry on a particular session. Any suggestions? -
Call nested Serializer's .update() method
I have a JSONField in my model that stores some configuration data. I want to access this field (both read and write) with ability to make partial updates of inner fields and their values. For purpose of example let a model be called MyModel with JSONField called config: class MyModel(models.Model): config = JSONField(default=dict()) ... I created a separate ViewSet to access information stored in config field. Assume that user model has ForeignKey relation to MyModel. Simplified version of this ViewSet is: class ConfigurationFieldViewSet(mixins.RetrieveModelMixin, mixins.UpdateModelMixin, viewsets.GenericViewSet): serializer_class = MyModelConfigurationSerializer def get_object(self): return self.request.user.my_model Data stored in config has a certain structure with several possible inner objects: { "C1": {"counter": 42, "active": false}, "C2": {"counter": 13, "active": true} } To access and correctly serialize MyModel instance at higher level I have created a serializers for each level of field. To acces config field in MyModel itself I'm using this serializer: class MyModelConfigurationSerializer(serializers.ModelSerializer): configuration = ConfigurationFieldSerializer(required=True) class Meta: model = MyModel fields = ('configuration',) To access and serialize first layer of configuration field there's second serializer: class ConfigurationFieldSerializer(serializers.Serializer): C1 = BaseConfigurationSerializer(required=True) C2 = BaseConfigurationSerializer(required=True) At last to access inner structure of each C1 and C2 fields there's third serializer: class BaseConfigurationSerializer(serializers.Serializer): counter = … -
Model creation order when testing in django?
I’ve got these two models (examples) and when I’m trying to run my tests - it errors out saying: no such table: my_app_modelA - if I scroll up I can see that it is bombing out when creating modelB (which I assume is due to the default being applied). Is there a way to order these so that modelA will always get created before modelB? Or should I not be referencing that method as a default attribute? Just trying to get my tests working and this is my sticking point. My models look like this: class modelA(models.Model): attribute = models.IntegerField() active = models.BooleanField(default=False) @classmethod def get_active_attribute(cls): return modelA.objects.get(active=True).attribute class modelB(models.Model): attribute = models.IntegerField(default=modelA.get_active_attribute()) My questions are: Is that an acceptable thing to do - having default call another model method? Is there a way to handle the creation of those models in a way that I can guarantee that modelA gets created first so modelB can succesfully create in my tests? -
Access 'request' in ViewSet (to be used for user filtering)
From what I have read in the documentation, the Request object should be accessible to be used in the view. However, when I access it either in base view or in 'get_queryset' - it doesnt seem to 'exist': class TestViewset(viewsets.ModelViewSet): depth = 1 serializer_class = TestSerializer def get_queryset(self): user = self.request.user return Test.objects.filter(user=user) Specifically, it returns and error telling me that request is not an attribute available. How does one access the request object in a viewset? -
How do you add new data to request.data?
What I'm trying to achieve is add sid to request.data so I can get it to my serializer but I'm not entirely sure how to achieve this. Can I append it somehow or do I have to have a separate serializer just for sid? class Test001(APIView): def __init__(self): self.account_sid = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' self.auth_token = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' self.twilio_number = 'whatsapp:+14XXXXXXXX' self.to_number = 'whatsapp:+14XXXXXXXXX' def post(self, request): client = Client(self.account_sid, self.auth_token) new_message = client.messages.create( from_=self.twilio_number, body=message, to=self.to_number ) sid = new_message.sid serializer = MessageSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
deleting objects without refresh django
I am trying to delete selected objects in django it works but when I select an item then click delete button it does not delete but after it when I refresh the page selected object is deleted. Here is views.py @login_required def delete_contact(request): if request.is_ajax(): selected_contacts = request.POST['contact_id'] selected_contacts = json.loads(selected_contacts) for i, contact in enumerate(selected_contacts): if contact != '': ClientContact.objects.filter(author_id__in=selected_contacts).delete() return redirect('contacts') in templates <table class="table table-hover contact-list"> <thead> </thead> {% for contact in contacts %} <tbody> <tr data-id="{{ contact.id }}" class="clickable-row" data-href="{% url 'contact-detail' contact.id %}" style="cursor: pointer; "> <th scope="row"><input type="checkbox" id="check"></th> <td>{{ contact.client_name }}</td> <td>{{ contact.client_company_name }}</td> <td>{{ contact.email }}</td> <td>{{ contact.work_phone }}</td> <td>{{ contact.work_phone }}</td> </tr> </tbody> {% endfor %} </table> {% csrf_token %} </div> </div> </div> </div> {% include 'users/footer.html' %} <script type="text/javascript"> $(document).ready(function () { $(".delete-btn").click(function () { var selected_rows = []; $('.contact-list').find('tr').each(function () { var row = $(this); if (row.find('input[type="checkbox"]').is(':checked')) { console.log(row.attr('data-id')); selected_rows.push(row.attr('data-id')); } }); var selected_rows = JSON.stringify(selected_rows); $.ajax({ url: "{% url 'contact-delete' %}", type: 'POST', data: { 'contact_id': selected_rows, 'csrfmiddlewaretoken': $("[name=csrfmiddlewaretoken]").val() }, }); }); }); </script> it works fine but with refreshing the page. How can I delete selected objects as soon as I click the delete button. Any help … -
What's the `index` of Django?
I'm trying to switch from PHP to Python, specifically using Django. I've been a PHP developer for many many years and that means that my mindset is more or less following a pattern that i'm used to. I've installed Python and Django via docker, i created a project, i started an app, ran the migrations, in general i think everything is ready to start coding. Now my question is, where do i start? What's the index file for Django? To be more accurate, what's the index.php of Django? For example, in almost any PHP framework there's the index.php in your public directory and then it loads everything else (configs, middleware, etc.). In that index.php you can do whatever you want(bad practice of course) like die('hello') or echo 'hello' and so on. Or ok let's be more realistic, you can set the default controller and type whatever you want in the index action function and start typing whatever you want(pure PHP or whatever). How do i do the same in Django? Is it possible after all? -
How to calculate total hours in my Timesheet model?
I'm setting two models, Timesheet and TimesheetEntry. TimesheetEntry will be inline and is set it in admin.py file and from there you can put the current hours per project. My question is how to make function and calculate the total_hours so I can visualize it in my custom table in Django template ? class TimesheetEntry(TimeStampedModel): hours = models.DecimalField(max_digits=4, decimal_places=2, default=0, verbose_name=_("Hours")) timesheet = models.ForeignKey('timesheet.TimeSheet', verbose_name=_("Timesheet"), related_name='timesheet_entries', on_delete=models.CASCADE) project = models.ForeignKey('project.Project', verbose_name=_("Project"), related_name='timesheet_entries', on_delete=models.PROTECT, null=True) project_role = models.ForeignKey('project.ProjectRole', verbose_name=_("Project role"), related_name='timesheet_entries', on_delete=models.PROTECT, null=True) def __str__(self): return f"{self.timesheet} - {self.project} - {self.project_role}" def save(self, **kwargs): self.timesheet.save() super().save(**kwargs) class Meta: verbose_name = _("Timesheet entry") verbose_name_plural = _("Timesheet entries") class Timesheet(TimeStampedModel): date = models.DateField(verbose_name=_("Date"), default=datetime.date.today, editable=True) total_hours = models.DecimalField(max_digits=4, decimal_places=2, verbose_name=_("Total hours"), editable=False) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='timesheet') def __str__(self): return f"{self.user} - {date_format(self.date, 'DATE_FORMAT')}" def recalculate(self): self.total_hours = self.timesheet_entries.all().aggregate(total_hours=Sum('hours'))['total_hours'] or 0 def save(self, **kwargs): self.recalculate() super().save(**kwargs) def projects(self): from hr.project.models import Project return Project.objects.filter( pk__in=self.timesheet_entries.all().values_list('project_id', flat=True).distinct() ) class Meta: verbose_name = _("Timesheet") verbose_name_plural = _("Timesheets") ``` -
Conditional Serializer Class In Request Method
I am creating a single api for create or update. So if the auth user does not exist it will get created and if exists it will check for any update in the profile attributes. So I have used PATCH method where I can create as well as update. I want to create two serializer class one EmployeeCreate and another EmployeeUpdate. As the patch request would hold the request data I can find weather the user is already there or not and then I want to select the serializer class inside the PATCH method. I cannot even use the get_serializer_class(), as i have to define the serializer class before all methods. In Views: class AddEMPLOYEE(AllCreateErrorPatch, UpdateAPIView): queryset = UserProfile.objects.all() authentication_classes = [TokenAuthentication, ] permission_classes = [IsAdminUser] serializer_class = None def patch(self, request, *args, **kwargs): print(self.get_serializer_class()) serializer = self.get_serializer(data=request.data) if not serializer.is_valid(): return self.response_error(serializer.errors) req_data = serializer.validated_data if User.objects.filter(email=request.data['email']).count()==0: serializer_class = EmployeeCreate user_fields = ["email", "first_name", "last_name", "password"] user_data = {field: req_data[field] for field in user_fields} for field in user_fields: del req_data[field] user_serializer = UserSerializer(data=user_data) if not user_serializer.is_valid(): return self.response_error(user_serializer.errors) user_serializer.save() req_data['user'] = user_serializer.data["id"] else: serilaizer_class = EmployeeUpdate user_profile = UserProfile.objects.get(user=User.objects.get(email=request.data['email'])) user_profile_serializer = UserProfileSerializer(user_profile, data=req_data, partial=True) if not user_profile_serializer.is_valid(): return self.response_error(user_profile_serializer.errors) … -
Integration of razorpay into postgres sql database after submitting a payment button
I have build payment gateway to my site using razorpay with all auth details after submitting a pay button, the detils such as payment id, amount,date, and other details must be updated to database(postgresql) with django framework.Kindly need help solving these issue Payment button is added to my site.The HTML file name is app.html and app file name is app.py. please find these two files.when tried running app.py it shows error. please find code for app.html below: <html> <head lang="en"> <meta charset="utf-8"> </head> <body> <form action="charge" method="POST"> <script src="https://checkout.razorpay.com/v1/checkout.js" data-key="XXXXXXXXXXXXXXX" data-amount="1000" data-name="Daft Punk" data-description="Purchase Description" data-image="vk.jpg" data-netbanking="true" data-description="Tron Legacy" data-prefill.name="Harshil Mathur" data-prefill.email="harshil@razorpay.com" data-prefill.contact="9999999999" data-notes.shopping_order_id="21"> </script> <input type="hidden" name="shopping_order_id" value="21"> </form> </body> </html> please find code for app.py below : import razorpay import json from flask import Flask, render_template, request app = Flask(__name__,static_folder = "static", static_url_path='') razorpay_client = razorpay.Client(auth=("xxxxxxxxxxxx","xxxxxxxxxxxxx")) @app.route('/') def app_create(): return render_template(r'E:\backup\user\Desktop\app.html') @app.route('/charge', methods=['POST']) def app_charge(): amount = 1000 payment_id = request.form['razorpay_payment_id'] razorpay_client.payment.capture(payment_id, amount) return json.dumps(razorpay_client.payment.fetch(payment_id)) if __name__ == '__main__': app.run() For the above code my primary goal is store attribute variables like amount, payment id, etc into my database from this payment gateway action. I'm a beginner in dgango and python, [ im a bad boy ] -
Django one to many relationship for API call in restframework
I have two models which are question and set of choices aligned with that question.I want to combine this two models to create API which shows list of question with their choices. This is my Models class which has both the models class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField("date published") def __str__(self): return self.question_text class Choice(models.Model): choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) question = models.ForeignKey(Question, on_delete=models.CASCADE) def __str__(self): return self.choice_text This is Serializers class which I have used class QuestionSerializer(serializers.ModelSerializer): class Meta: model = Question fields = ('question_text',) class ChoiceSerializer(serializers.ModelSerializer): class Meta: model = Choice fields = ('choice_text','question',) class QuestionWithAnswer(serializers.ModelSerializer): question = QuestionSerializer(many=True) class Meta: model = Choice fields = ('question',) Here is my views class @api_view(['GET', 'POST', ]) def getquestionWithChoices(request): question = Question.objects.all() serializer = QuestionWithAnswer return Response(serializer.data) I have tried many things but could not get the below output.Thanks in advance.## Expected output [ { "id": 1, "question_text": "What's your name?", "pub_date": "2019-04-13T05:27:21Z", "choices": [ { "id": 1, "choice_text": "fred", "votes": 0, "question": 1 }, { "id": 2, "choice_text": "bob", "votes": 0, "question": 1 }, { "id": 3, "choice_text": "rachel", "votes": 0, "question": 1 } ] }, { "id": 2, "question_text": "What's your age?", "pub_date": "2019-04-13T05:27:39Z", "choices": … -
Django poll app tutorial is not working as expected in my server
i am cuurently working on django poll app tutorial and i am getting this error . Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: polls/ admin/ The empty path didn't match any of these. already tried restarting the server ,migrate the data and settings.py having installed apps . however django tutorial doesnot ask you for this until now. working on windows 10 64 bit polls/urls.py from django.urls import path from . import views urlpatterns=[path('',views.index,name='index'),] mysite/urls.py from django.contrib import admin from django.urls import include,path urlpatterns=[path('polls/',include('polls.urls')),path('admin/',admin.site.urls')),] results should be response from the views.py file -
How to scan a file for potential ransomware infection in one drive
I’m currently working on an application that gives a protection to the client from ransomware in OneDrive storage . The app uses a website where the client puts his credentials for his Microsoft account, than authorize the access for the OneDrive storage. I’m using Microsoft-graph and Django, and Microsoft azure for database. I have an access to the account of the client via token. Now that I have the access I want to scan all the files that are currently in the storage for suspicious behaviors like encryption, outside communication etc.the only thing that I’m getting is a Json file (I’ve tried to download it) unfortunately I didn’t figure out how to do it, so how can I scan a file given a token and credentials of a client? This is an example for the function (python)that gets the token from the user and post it to main page: def get_one_drive_files(token): graph_client=Oauth2session(token=token) query_params={ 'select': 'name' } events= graph_client_get('http://graph.microsoft.com/v1.0..../drive/items') return events.json -
Why do we have to save instance of a profile when that profile is already created and saved?
I am following a tutorial in Django and I have some problem understanding code below: @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): print(instance) # nooruddin_khan if created: Profile.objects.create(user=instance) # why do we need to save instance? 'Profile.objects.create' already created and save that for us @receiver(post_save, sender=User) def save_profile(sender, instance, **kwargs): instance.profile.save() That means if a user create an account or sign up to the website, using signals a profile will be created automatically associated to that user. The question is that why do we need to save the instance of the profile because Profile.objects.create(user=instance) has already created and saved that instance simultaneously. Even if I omit the second block of above code it will still work fine: @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): print(instance) # nooruddin_khan if created: Profile.objects.create(user=instance) What am I missing here or I don't understand or is it that we don't need that second block? Please help me understand this and thank you in advance. -
Django_tables2 with Edit and Delete buttons. How to do it properly?
I'm building an app that lists, sorts, updates and deletes objects. How can I properly add edit and/or delete buttons to django-tables2 table render? Python version: 3.7 and Django version: 2.1.7 are used. I have tried multiple ways and searched on internet but it seems a little complicated to implement it with django-tables2 table rendering. I'm stuck with this for more than 6 hours. Here is my code. byauthor.html --table is rendered in this html {% extends "main/base.html" %} {% block content %} {% load render_table from django_tables2 %} <h3>Logged in: {{user.first_name}} {{user.last_name}} </h3> <p>{{ time|date:"d.m.Y." }}</p> {% render_table table %} {% endblock %} views.py def byauthor(request): current_account = request.user items = Cashier.objects.filter(user__exact=current_account).filter(cashier_published__date=datetime.today()) table = CashierTable(Cashier.objects.filter(user__exact=current_account).filter(cashier_published__date=datetime.today())) RequestConfig(request).configure(table) return render(request, 'main/byauthor.html', {'table': table, 'time': datetime.now(), 'items': items}) def delete_item(request, pk): Cashier.objects.filter(id=pk).delete() items = Cashier.objects.all() context = { 'items': items } return render(request, 'main/delete_confirmation.html', context) urls.py from django.urls import path from . import views app_name = 'main' # here for namespacing of urls. urlpatterns = [ path("", views.homepage, name="homepage"), path("byauthor", views.byauthor, name="byauthor"), path('byauthor/delete_item/<int:pk>', views.delete_item, name="delete_item"), ] Here I have added a column to a table model. tables.py class CashierTable(tables.Table): delete = tables.TemplateColumn(template_name='main/delete_template.html', orderable=False) class Meta: model = Cashier order_by = '-id' And … -
The best way for integration Django and Scrapy
I know some ways like scrapy-djangoitem but as it has mentioned: DjangoItem is a rather convenient way to integrate Scrapy projects with Django models, but bear in mind that Django ORM may not scale well if you scrape a lot of items (ie. millions) with Scrapy. This is because a relational backend is often not a good choice for a write intensive applications (such as a web crawler), specially if the database is highly normalized and with many indices. So what is the best way to use scraped items in db and django models? -
PyCharm: running Django tests with env file does not work
I'm trying to run unit tests from PyCharm without success in a Django project. Here is the architecture of my project: - fugo/ (root repository) - .env_test - fugoproj/ (django project repository) - config/ - settings.py I installed EnvFile plugin to load .env_test variable environments that are used by my settings.py. Then I created a Run/Debug configuration on Pycharm When running tests from this configuration, the Pycharm console displays a "There is no such settings file settings". Tests are found and run, but failed, because settings can obviously not be loaded. What's wrong with my configuration? Thanks. -
Gunicorn configuration - I think I might have done it wrong?
This is my first time configuring gunicorn. I've used a tutorial from DigitalOcean but I can't make it work. My files are like this: home/octavian56/robotics.carabella.ro/venv (here is the venv with bin and stuff)/robotics (with manage.py and stuff) Here is the /etc/systemd/system/gunicorn.service [Unit] Description=gunicorn daemon After=network.target [Service] User=octavian56 Group=www-data WorkingDirectory=/home/octavian56/robotics.carabella.ro ExecStart=/home/octavian56/robotics.carabella.ro/venv/robotics/bin/gunicorn --access-logfile - --workers 3 --bind unix:/home/octavian56/robotics.carabella.ro/venv/robotics/bin/robotics.sock robotics.wsgi:application and I'm getting errors. I can't seem to get why nad I don't have enough time to fix it because this website has to be deployed today. Can anyone help me explain how should I properly configure this? Thanks. -
Using firebase-admin sdk, i can see messages are sent, but they are not received on the device
I am trying to send push notifications to my android and ios apps using firebase cloud messaging and django backend. Per this doc - https://firebase.google.com/docs/cloud-messaging/send-message I get the following output after messaging.send() projects/avaasa-dev/messages/0:1555400295710341%fa6bca8ffa6bca8f which as i understand means the message is successfully sent. But i do not receive the notification on my device. I have also tried the django-push-notifications package instead of firebase-admin and i can see the notifications are received in the case. But, here my android team was having trouble handling the notification using OnMessageReceived function, so i am trying to use firebase-admin again. 1.In setting.py i have added 'firebase_admin' in the list of installed_apps Ran migrations i have written the below method to be invoked whenever a notification needs to be sent - import firebase_admin from firebase_admin import credentials cred = credentials.Certificate("avaasa-dev-firebase-adminsdk.json") fcm = firebase_admin.initialize_app(cred, name='avaasa_firebase') def PushNotification(user_ids=[], title='Avaasa Notification', message='This is the default Notification'): from firebase_admin import messaging devices = sometable_in_db.objects.filter(user_id__in=user_ids) print(devices) for device in devices: notification = messaging.Notification(title=title, body=message) msg = messaging.Message(token=device.registration_id, notification = notification, data={'title': title, 'body': message}) msg_ = messaging.send(msg, app=fcm) print(msg_) I see that the following is returned for a message - projects/avaasa-dev/messages/0:1555400295710341%fa6bca8ffa6bca8f But no notification received on the device. The token … -
filterd queryset for foreginkey
My application design requires that an Airflow DAG, which is currently being executed, can be paused if executing, resume if paused and stopped. This is different from the pause/unpause functionality provided. For example, if a DAG has 8 components and 3 components have already executed successfully. Now I want to pause the execution of this DAG. After some time, I want to resume that paused DAG. After 6 components, I realised that this DAG has a major flaw and I need to terminate its execution. I tried to look for these three functionalities in the CLI documentation but could not find these functions. API documentation also does not tell about any API which can do this. Would request Airflow veterans to suggest on this. -
Does Core amount matters for news website focused on multi user?
I have recently created my first Django project and want to deploy. Project is a news website. And it is expected to serve many people. So, sorry for stupid question, but does Core amount matters for such kind of websites? If yes how many Cores do I need for this project? I have searched for VPS/VDS servers and the cheapest one is for about 4$ (cheapest is focused). It has 1 Core, 30 GiB SSD and etc... -
Non-binary LIKE operation through Django ORM
This is a follow-up from this question. Although I can write a non-binary LIKE query such as - SELECT COUNT(*) FROM TABLE WHERE MID LIKE 'TEXT%' in raw SQL, I would like to know if it's possible through the Django ORM. Both startswith and contains seem to be using a binary pattern search. -
Searching Django database including ManyToManyField
I am quite new django but have read into select_related and prefetch_related. However I am unable to build a search function that can cover both the OneToMany relations and ManyToMany. My Model: class Tag(models.Model): tag = models.CharField(max_length=50, blank=False, unique=True) def __str__(self): return self.tag class Course(models.Model): title = models.CharField(max_length=10) description = models.CharField(max_length=200, blank=True, null=True) startdate = models.DateTimeField() stopdate = models.DateTimeField() teacher = models.ForeignKey( Teacher, blank=True, null=True, on_delete=models.PROTECT ) tags = models.ManyToManyField(Tag, blank=True) classroom = JSONField(default=json.loads("{}"), blank=True, null=True) def __str__(self): return "[ {0} ] {1}-{2}".format(self.id, self.title, self.description) def startdate_custom(self): return self.startdate.strftime("%Y-%m-%d") In my view I have a class where I want to be able to query (using a search function) over all the columns/tables (title, description, teacher, tags, classroom) in the database. Examples below are simpified: I can build queries on the main table: search = 'Api' qs = self.model.objects.select_related('teacher').prefetch_related('tags') qs = qs.filter(description__icontains=search) This approach works for title, description, teacher... but not for my ManyToManyField I can however I cannot extend that filter to the tags search = 'Api' qs = self.model.objects.select_related('teacher').prefetch_related('tags') qs = qs.filter(tag__icontains=search) <-- does not work It seems however, I can filter out tags by iterating over tags : tags_qs = self.model.objects.all().prefetch_related('tags') tags_list = [list(course.tags.filter(tag__icontains='API')) for course in tags_qs] …