Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to delete an specific item from a foreign key within .views? Django
Im working on a Django app where you can join events only under the approval of the owner of the event. By now, I have the function that adds the current user to the event for approval. .views @login_required def request_event(request, pk): previous = request.META.get('HTTP_REFERER') try: post = Post.objects.get(pk=pk) Attending.objects.create(post=post, attendant=request.user) messages.success(request, f'Request sent!') return redirect(previous) except post.DoesNotExist: return redirect('/') and here is the function that deletes de user request (By now is deleting the request of the current logged user) @login_required def remove_attendant(request, pk): previous = request.META.get('HTTP_REFERER') try: post = Post.objects.get(pk=pk) #attendant = #post.attending_set.all Attending.objects.filter(post=post, attendant=request.user).delete() messages.success(request, f'User removed!') return redirect(previous) except post.DoesNotExist: return redirect('/') My situation here is that I'm a having problem to get the attendants of the event (all the users who where added as atendant), so that the owner can reject which ever request he want. How can I change this so that the function is going to delete a specific user of the event? Thanks!! Additional: models.py class Attending(models.Model): is_approved = models.BooleanField(default=False) attendant = models.ForeignKey(User, related_name='events_attending', on_delete=models.CASCADE, null=True) post = models.ForeignKey('Post', on_delete=models.CASCADE, null=True) class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) urls.py path('post/<int:pk>/remove_attendant/', views.remove_attendant, name='remove-attendant'), -
Django - how to create a form field containing checkboxes WITH an 'Other' text input field
I'm creating a form in Django, and would like to give users a list of checkboxes with the option of having an Other _____ text input as one of the choices. Here's my code using MultipleChoiceField and CheckboxSelectMultiple: class IntakeFormSimple(Form): def __init__(self, *args, **kwargs): super(IntakeFormSimple, self).__init__(*args, **kwargs) preferred_pronouns = forms.MultipleChoiceField( choices=(("she/her", "she/her"), ("he/him", "he/him"), ("they/them", "they/them")), # <--- add "Other" here label="What are your preferred pronoun(s)?", widget=forms.CheckboxSelectMultiple, ) -
How to implement a low cost (semi) chat in django/mobile app
I want to implement a semi (realtime) web chat. The project has 2 user groups, Managers and Users. The manager is in a group chat with his users. There are a couple of demands/problems: Now the thing is django is hosted on pythonanywhere, they dont support websocket. The cost of the project has to be low so streamer is not an option for now. I can do it over rest api but there will be a lot of requests on the server side, i dont know if this is a problem over time. Anyone done a project like this ? please advise. -
How to use Django's hidden `through` models in a `Q` expression
I learned yesterday that you can use a through expression in a key path that's in a Q expression. And I learned that when filtering using fields in M:M related tables, the resulting queryset is more like a true join (where the root table record is duplicated and combined with multiple related table records). I learned that I could accomplish this using ModelA.mmrelatedModelB.through.filter() in the shell. For example, I have 106 PeakGroup records, and every PeakGroup for compound "citrate" also links to compound "isocitrate", so if I query for 1, I get back 106 records. And if I query for either, I get back 212: In [16]: PeakGroup.compounds.through.objects.filter(Q(compound__name__exact="citrate")).count() Out[16]: 106 In [17]: PeakGroup.compounds.through.objects.filter(Q(compound__name__exact="citrate") | Q(compound__name__exact="isocitrate")).count() Out[17]: 212 However, I learned in the comments under this stack answer, that I should be able to accomplish the same thing in the Q expression only, without referencing PeakGroup.compounds.through. I imagined the expression might look something like this: PeakGroup.objects.filter(Q(through_peakgroup_compound__compound__name__exact="citrate") | Q(through_peakgroup_compound__compound__name__exact="isocitrate")).count() but I have been unable to figure out how to construct the "path" that includes the through model... Every attempt results in an error something like: FieldError: Cannot resolve keyword 'through_peakgroup_compound' into field. Perhaps in the comments of that linked stack answer, there … -
what's gettext_lazy on django is for?
maybe is a dummy question but i have read on the documentation of Django about the "gettext_lazy", but there is no clear definition for me about this exact function and i want to remove it and i found this implementation from django.utils.translation import gettext_lazy as _ and is used on a django model field in this way email = models.EmailField(_('email address'), unique=True) what's is for? what's happen if i remove it? -
how do I request a user and save the user in a Foreignkey field of a model
I've been at it for some time but can't find a way to set the 'customer' to the 'ShippingAddress' model's customer foreignkey field, how do I query the customer field so that along with the shipping data through the form, the customer gets saved in the foreignkey field as well. thx in advance! **models.py** class Customer(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, blank=True, null=True) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField(max_length=150) class ShippingAddress(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) address_one = models.CharField(max_length=200) address_two = models.CharField(max_length=200) ... **views.py** def checkout(request): if request.method == 'POST': form = ShippingForm(request.POST) customer = request.user.customer if form.is_valid(): # how to get the customer and send it back to the shippingmodel form user = ShippingAddress.objects.get(customer=customer) form.save() return redirect('store:checkout_shipping') else: form = ShippingForm() else: form = ShippingForm() context = {"form": form} return render(request, 'store/checkout.html', context) -
Configuring multiple databases in Django
Introduction I have read Django docs: Multiple databases, but it doesn't seem to work for me after upgrading from 3.2 to 4.0. Other changes have been made, but since I'm working in a development environment, I chose to remove all previous migrations and run ./manage.py makemigrations again, but it did not help to solve the issue. Router Definition First, here's how I define the router. You'll notice it's nearly identical to the example, but I include mostly everything in the admin_db database (with two exceptions: custom apps api.dictionary and api.pdf). /api/authentication/routers.py class AdminDBRouter: """ A router to control all database operations on models in the authentication application, all and any dependent applications, and Django administrative applications. """ route_app_labels = { 'admin', 'auth', 'authentication', 'contenttypes', 'sessions', 'sites', 'token_blacklist', } def db_for_read(self, model, **hints): """ Attempts to read models defined in any app in 'self.route_app_labels' go to 'admin_db'. """ if model._meta.app_label in self.route_app_labels: return 'admin_db' return None def db_for_write(self, model, **hints): """ Attempts to write models defined in any app in 'self.route_app_labels' go to 'admin_db'. """ if model._meta.app_label in self.route_app_labels: return 'admin_db' return None def allow_relation(self, obj1, obj2, **hints): """ Allow relations if a model in any app defined in 'self.route_app_labels' is … -
Migrating my Django project on Heroku is showing django.db.utils.ProgrammingError: relation "users_customuser" does not exist
Migrating my Django project on Heroku is showing django.db.utils.ProgrammingError: relation "users_customuser" does not exist. But this is working completely fine on my local. Running migrations: Applying account.0001_initial...Traceback (most recent call last): File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "users_customuser" does not exist The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/app/manage.py", line 22, in <module> main() File "/app/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/commands/migrate.py", line 244, in handle post_migrate_state = executor.migrate( File "/app/.heroku/python/lib/python3.9/site-packages/django/db/migrations/executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/migrations/executor.py", line 230, in apply_migration migration_recorded = True File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/base/schema.py", line 118, in __exit__ self.execute(sql) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/base/schema.py", line 145, in execute cursor.execute(sql, params) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/utils.py", line 98, in execute return super().execute(sql, params) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/utils.py", line 66, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/utils.py", line 75, … -
Problems with JSON data can't get it rendered on template
I have the models.py with employee and all the info. With one click i want to render all the info of my employee. the thing is, I have 2 columns one for names and one for information. when i click a name the right column has to come up with the array with name last name..... i can see it on the console but i can't get it rendered. Think i have problems with the key but i dont know. here is the code.. views.py in this function i want to get the id of the name by jsonloads by clicking the name and filter the employe with it.(this works) def check(request): if request: if request.method == 'POST': data = json.loads(request.body) employeId = data['id_s'] empinfo = Employe.objects.filter(id=employeId) print(empinfo) print(data) return JsonResponse({'data': list(empinfo.values())}, safe=False, status=200) return HttpResponse() js code is here. in these code i want to get the data by fetch url. i can see it on the console log that the data is recieved(these function works good aswel) function checkEmp(id_s, action){ var url = '/checks/' fetch(url, { method: 'POST', headers:{ 'Content-Type':'application/json', 'X-CSRFToken': csrftoken, }, body:JSON.stringify({'id_s': id_s, 'action': action}) }) .then((response)=>{ return response.json() }) .then((data)=>{ console.log(data); }) } index.html i … -
how do i remember the radio button selection in django
i'm trying to make sure that even if the user refresh the page or goes back and comes back to that page, the radio button is still the same as what the user selects. N.B: the value of the radio button is saved in sessions <div class="col-md-1 ps-md-1"> <input class="align-middle h-100" type="radio" name="deliveryOption" id="{{option.id}}" value="{{option.id}}"> </div> my ajax $('input[type=radio][name=deliveryOption]').on('change', function(e) { e.preventDefault(); $.ajax({ type: "POST", url: '{% url "checkout:cart_update_delivery" %}', data: { deliveryoption: $(this).val(), csrfmiddlewaretoken: "{{csrf_token}}", action: "post", }, success: function (json) { document.getElementById("total").innerHTML = json.total; document.getElementById("delivery_price").innerHTML = json.delivery_price; }, error: function (xhr, errmsg, err) {}, }); }); </script> my view def cart_update_delivery(request): cart = Cart(request) if request.POST.get("action") == "post": delivery_option = int(request.POST.get("deliveryoption")) delivery_type = DeliveryOptions.objects.get(id=delivery_option) updated_total_price = cart.cart_update_delivery(delivery_type.delivery_price) session = request.session if "purchase" not in request.session: session["purchase"] = { "delivery_id": delivery_type.id, } else: session["purchase"]["delivery_id"] = delivery_type.id session.modified = True response = JsonResponse({"total": updated_total_price, "delivery_price": delivery_type.delivery_price}) return response -
Django annotate count of disctinct values of the running quesyset in its children
I was tracing this bug for a while until I found the source I believe it's coming from, and I have been stuck here now. I have the following models below: class ShopItem(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) store = models.ForeignKey(to=Store, on_delete=models.CASCADE) name = models.CharField(max_length=250) class SelectedProduct(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name="products", null=True, blank=True) product = models.ForeignKey(ShopItem, null=True, blank=True, on_delete=models.SET_NULL) class Order(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) store = models.ForeignKey(Store, on_delete=models.CASCADE, related_name="orders") status = models.PositiveIntegerField(choices=OrderStatus.choices, default=OrderStatus.CART) number = models.CharField(max_length=36, blank=True, null=True) Lets say for example an order has 5 products, 3 of these products are of the same type (p1, p2, p3) as they reference same shop item; where are the other two products (p4, p5) are different since they reference different shop items. I am trying to annotate how many same products exist on this order as in the following products = order.products.all().annotate(quantity=Count("product")) Attempting to get a queryset of these products with quantity annotated, only thing, I get quantity of 1 for all products, where I am trying to get: p1.quanity > 3 p2.quanity > 3 p3.quanity > 3 p4.quanity > 1 p5.quanity > 1 is there anyway I could … -
How to delete localstorage item from AJAX DOM?
I have localstorage itemcheck on following format: {"images":["png1"],"itemIds":["1","3","4"]}' On Ajax success, DOM is passed on following way: success: function (data) { console.log(data) $.each(data, function (key, value) { if ($.trim(key) == "products") { for (var i = 0; i < data[key].length; i++) { var wishlistUrl = "{% url ecommerce:add_to_wishlist %}"; var featured_image = data[key][i]['featured-images'][0]['image'] var div = '<a href="#" class="btn remove-product"><i class="w-icon-times-solid" id="remove_compare" attr="' + data[key][i].id + '"></i></a>'; $("#items").append(div); On #remove_compare button click, I want to remove item from localstorage having itemIds equal to attr value inside ajax DOM. How can I do this? -
registering user in django des not work and it does not gievs me any error
I was working on a simple register veiw that sends activation code too in django . And the problem is that it does not gives me any error and It does not register any user and I dont know why? Here is my code : veiws.py : def register_page(request): if request.method == 'POST' : form = forms.UserRegister(request.POST) if form.is_valid(): data = form.cleaned_data if data['password_1'] != data['password_2'] and '@' in data['email'] and data['username'] != data['email'] and not User.objects.filter(username = data['username']).exists(): user = User.objects.create_user(username=data["username"] , email = data['email'] , password = data['password1'] , is_active = False) user.save() v = randint(1000 , 5000) subject = 'sample subject' message = f'your code : {v}' email_from = settings.EMAIL_HOST_USER recipient_list = [data['email'] , ] send_mail( subject, message, email_from, recipient_list ) active_code.objects.create(code = v , email = data['email']).save() return redirect('home:activeveiw') else: if data['username'] == data['email']: messages.error(request ,'error 506') if User.objects.filter(username = data['username']).exists(): messages.error(request ,'error 789') if data['password_1'] != data['password_2'] : messages.error(request , 'error 899') else : form = forms.UserRegister() con = {"form" : form } return render (request , 'home/register.html' , con) template : <form action="" method="post"> {% csrf_token %} <input type="text" name="username"> <input type="text" name="email"> <input type="text" name="password_1"> <input type="text" name="password_2"> <button type="submit">send</button> </form> {% if … -
How to show the saved data of 3 forms in my template in Django?
let's say I have a form_1, a form_2 and a form_3, all three forms store information and they are in different html pages. I would like to have a view that presents the information saved in forms 1, 2 and 3 in the same template. How can I do that? -
Can I integrate a django project to an android app?
I am a beginner (about 1 year since i started learning python on web) I was working on a project (for online video conferencing) you can check the developement here (JUST CLICK THE MAKE A MEETING BUTTON) https://pranaam.web.app but now i am in a doubt that i know basic JS (not node) HTML/CSS and python and if i am working on my project then i want to launch it on android platform like in ZOOM meetings we can both join from browser and the exe/apk is there a way to integrate my online functioning website to a mobile app (using python as i dont know any other languages) and also Organise all the buttons and functions in mannered way (not a messed up web view) -
How to abort model instance deletion from django model admin interface based on some condition
I want to abort model deletion from django admin based on some condition. I tried overriding delete_queryset(self, request, queryset) method. def delete_queryset(self, request, queryset): if (<my condition>): message = "Error message" raise ValidationError(message) super().delete_queryset(request, queryset) This doesn't work since django does not handles exception at this stage. -
How can access input value in django view through AJAX without form submission
I am beginner in django.I am working on a single text box in a django form which have number of fields.I wrote AJAX code for passing each value(entered from keyboard). How can i access this value in django class based view code. I want to save this value into a variable. Here i am trying to check given text is already existing or not. checking is done for each keyboardinput. $(document).ready(function () { $('#s_id > input').on('input',function(e){ console.log(e); s_text = e.target.value; $.ajax({ type: 'POST', url: "{% url 'create-studentpage' %}", data: s_text, success: function (response) { console.log("response", response); }, error: function (response) { console.log("error", response.responseJSON.error); } }) }); -
django - model foreign key as logged user
I've got model code as follows: from django.db import models from django.core.validators import MinLengthValidator from django.urls import reverse from django.conf import settings class Doc(models.Model): ... added_by = models.CharField(blank=False,null=True,max_length=100,validators=[MinLengthValidator(10)]) added_by_2 = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ... I can migrate this without any problems, but every when I run server and in admin site try to view all records I get: Exception Type: OperationalError Exception Value: no such column: added_by_2_id What is the cause of this error? How to resolve it? -
Foreign key of foreign key in django-polymorphic
I have the following (simplified) django and django-polymorphic models: class GenericOffer(PolymorphicModel): pass class OfferA(GenericOffer): special = models.IntegerField() class OfferB(GenericOffer): pass class GenericProduct(PolymorphicModel): offer = models.ForeignKey(to=GenericOffer) class ProductA(GenericProduct): pass class ProductB(GenericProduct): pass class Gizmo(models.Model): product = models.ForeignKey(to=GenericProduct) from which I can create the following instances: offer_a = OfferA() product_a = ProductA(offer=offer_a) gizmo_a = Gizmo(product=product_a) Now, I have: assert product_a.offer == offer_a assert gizmo_a.product == product_a But: assert gizmo_a.product_a.offer != offer_a assert gizmo_a.product_a.offer.get_real_instance() == offer_a That is, the foreign key linked to a foreign key of my Gizmo is not automatically cast to its proper type. Is it the expected behavior? Should I use a GenericRelation instead of a ForeignKey in my Gizmo ? Thanks for any advice -
Django view testing (sessions , ajax )
In django e-commerce project, i have view which adds a product in basket via sessions, also this view getting POST request from ajax. I can't find how to test this code. basket/views.py def basket_add(request): basket = Basket(request) if request.POST.get('action') == 'post': product_id = int(request.POST.get('productid')) product_qty = int(request.POST.get('productqty')) product = get_object_or_404(Product, id=product_id) basket.add(product=product, qty=product_qty) basketqty = basket.__len__() response = JsonResponse({'qty': basketqty}) return response basket/basket.py class Basket(): """ A base Basket class, providing some default behaviors that can be inherited or overrided, as necessary. """ def __init__(self,request): self.session = request.session basket = self.session.get(settings.BASKET_SESSION_ID) if settings.BASKET_SESSION_ID not in request.session: basket = self.session[settings.BASKET_SESSION_ID] = {} self.basket = basket def add(self,product,qty): """Adding and updating the users basket session data """ product_id = str(product.id) if product_id in self.basket: self.basket[product_id]['qty'] = qty else: self.basket[product_id] = {'price': str(product.regular_price),'qty':int(qty)} self.save() how to catch this piece of code in testing? <button type="button" id="add-button" value="{{product.id}}" class="btn btn-success fw500">Add to basket</button> <script> $(document).on('click', '#add-button', function (e) { e.preventDefault(); $.ajax({ type: 'POST', url: '{% url "basket:basket_add" %}', data: { productid: $('#add-button').val(), productqty: $('#select option:selected').text(), csrfmiddlewaretoken: "{{csrf_token}}", action: 'post' }, success: function (json) { document.getElementById('basket-qty').innerHTML = json.qty }, error: function (xhr, errmsg, err) {} }); }) </script> -
Correct way to define list parameter in django-rest-framework and swagger
Background I have the following view and the accompanying swagger UI is generated by django-spectacular: class AllowedNameType(Enum): BRAND = "BRAND" .... @classmethod def list(cls): return list(map(lambda c: c.value, cls)) class GenerateCompanyNamesViewSet(viewsets.ViewSet): http_method_names = ["get"] def list(self, request: Request, *args, **kwargs) -> Response: """Generate suggested company names""" # query_params: dict = {} allowed_name_types: list[AllowedNameType] = query_params.get("allowed_name_types") suggestions: list[Suggestion] = ... return Response(serializers.SuggestionSerializer(suggestions).data) I want to achieve the following: The swagger UI should have a parameter allowed_name_types which is a list of AllowedNameType values The input should be validated as per the serializer definition Type checking should be enforced on query_params to make sure the allowed_name_types is of type list[AllowedNameType] (ideally, allowed_name_types would actually be a named parameter in (eg list(..., allowed_name_types: list[AllowedNameType]) Attempted Solution class AllowedNameTypesParamSerializer(rest_framework_serializers.Serializer): allowed_name_types = rest_framework_serializers.ListField( child=rest_framework_serializers.ChoiceField(choices=models.AllowedNameType.list()), required=False, allow_empty=True, ) and added the following decorator to the list method: @extend_schema( parameters=[ OpenApiParameter(name="allowed_name_types", required=True, type=AllowedNameTypesParamSerializer), ], responses=serializers.FoodSearchAutoCompleteSerializer, ) def list(....) This leads to the following interface: Unfortunately: The swagger component expects a dictionary of {"allowed_name_types:...} instead of a list the allowed_name_types validation of list elements does not work (i.e I can put a value in the list that is not from AllowedNameType) Strangely, calling request.query_params.get('allowed_name_types') only returns the last … -
Postgresql docker: SCRAM authentication requires libpq version 10 or above
Trying to use PostgreSQL 14 with Django using docker-compose version: '3.7' services: web: build: context: . dockerfile: Dockerfile container_name: dev__app image: backend-dev command: ["/scripts/docker/wait_for_it.sh", "database:5432", "--", "/scripts/docker/docker_start.sh"] volumes: # Make /src directory editable which updates django app when code is changed - ./src:/app depends_on: - database env_file: - .env environment: - DATABASE={'ENGINE':'django.db.backends.postgresql','NAME':'app_dev','USER':'app_dev','PASSWORD':'app_dev','HOST':'database','PORT':'5432'} - CELERY_BROKER_URL=amqp://rabbitmq ports: - "8000:8000" restart: on-failure # database service database: image: postgres:14 container_name: app_db environment: POSTGRES_PASSWORD: app_dev POSTGRES_USER: app_dev POSTGRES_DB: app_dev POSTGRES_HOST_AUTH_METHOD: md5 POSTGRES_INITDB_ARGS: "--auth-host=md5" volumes: - app_database:/var/lib/postgresql/data ports: - "5432:5432" But every time I run it using docker-compose up --build It gives the following error django.db.utils.OperationalError: SCRAM authentication requires libpq version 10 or above -
How to use SearchHeadline with SearchVector on multiple fields
I need a search that searches multiple fields and returns a "headline" which highlights the matching words. My understanding is that SearchVector is the appropriate choice for searching across multiple fields. But all of the examples I've seen of SearchHeadline use only a single field! What's the best way to use SearchHeadline with multiple fields? For example, this works: return ( Author.objects .annotate(search_vectors=SearchVector('name', 'location'), ) .filter(search_vectors=SearchQuery(search_string)) ) Easy. So the next step is to add SearchHeadline... Here was my guess, but it causes an error in PostgreSQL: return ( Author.objects .annotate(search_vectors=SearchVector('name', 'location'), ) .annotate(headline=SearchHeadline( SearchVector('name', 'location'), SearchQuery(search_string), start_sel='<strong>', stop_sel='</strong>')) .filter(search_vectors=SearchQuery(search_string)) ) Error: Traceback (most recent call last): File "/vagrant/venv/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedFunction: function ts_headline(tsvector, tsquery, unknown) does not exist LINE 1: ...app_author"."location", '')) AS "search_vectors", ts_headlin... ^ HINT: No function matches the given name and argument types. You might need to add explicit type casts. Is SearchVector() not a valid expression? Using Concat() gets the job done, but this doesn't allow me to leverage the built in indexing capabilities of a ts_vector. It feels like a hack solution to me. return ( Author.objects .annotate(search_vectors=SearchVector('name', 'location'), ) .annotate(headline=SearchHeadline( Concat(F('name'), Value(' '), F('location')), SearchQuery(search_string), start_sel='<strong>', stop_sel='</strong>')) .filter(search_vectors=SearchQuery(search_string)) … -
Is using any with a QuerySet unoptimal?
Many times, one needs to check if there is at least one element inside a QuerySet. Mostly, I use exists: if queryset.exists(): ... However, I've seen colleagues using python's any function: if any(queryset): ... Is using python's any function unoptimal? My intuition tells me that this is a similar dilemma to one between using count and len: any will iterate through the QuerySet and, therefore, will need to evaluate it. In a case where we will use the QuerySet items, this doesn't create any slowdowns. However, if we need just to check if any pieces of data that satisfy a query exist, this might load data that we do not need. -
In Django, how do you enforce a relationship across tables without using constraint?
I'm creating a simple list app that has Groups and Items, each with an associated User. How can I enforce, in the model, that an item created by one user can never be linked to a group created by another user? Here's the model: class Group(models.Model): name = models.CharField(max_length=200) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) class Item(models.Model): name = models.CharField(max_length=200) group = models.ForeignKey(Group, on_delete=models.PROTECT) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) I've figured out this is impossible to do with a CheckConstraint in class Meta because constraints are apparently made in the database itself (I'm using postgres) and cross-table constraints are not allowed. Coding without a framework, you would simply query the group before saving a link and throw an exception if the users didn't match. So how do you do that in django?