Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to conntect this python file to django file ? Please tell me what shoud i do next ? im creating face recognition using opencv in django
import cv2 from time import sleep def capturewebcam(image): key = cv2. waitKey(1) webcam = cv2.VideoCapture(0) sleep(2) while True: try: check, frame = webcam.read() print(check) # prints true as long as the webcam is running print(frame) # prints matrix values of each framecd cv2.imshow("Capturing", frame) key = cv2.waitKey(1) if key == ord('s'): cv2.imwrite(filename='studnet_images/saved_img.jpg', img=frame) webcam.release() print("Processing image...") img_ = cv2.imread('saved_img.jpg', cv2.IMREAD_ANYCOLOR) print("Image saved!") break elif key == ord('q'): webcam.release() cv2.destroyAllWindows() break except(KeyboardInterrupt): print("Turning off camera.") webcam.release() print("Camera off.") print("Program ended.") cv2.destroyAllWindows() break i tried so many times bt i cant understand. Please help me to reslove the problem. -
How to get field value in django Model?
I have this code class Book(models.Model): name = models.CharField(max_length=70) author = models.CharField(max_length=70) rating = models.IntegerField(default=None) volume = models.IntegerField(null=True, default=None) annotation = models.TextField(default=None) year = models.IntegerField() I want to get a value from field right in class. For example, "Harry Potter" for name. I don't find method to do it. -
selenium: Max retries exceeded with url
Full traceback: Traceback (most recent call last): File "/home/webadmin/dev.taracares.com/src/app_payroll_reports/tests.py", line 134, in test_mstnla_sums_incentives_tennessee_sum int(quince_amount_cell.text.replace(',', '')) + File "/home/webadmin/dev.taracares.com/dev/lib/python3.8/site-packages/selenium/webdriver/remote/webelement.py", line 77, in text return self._execute(Command.GET_ELEMENT_TEXT)['value'] File "/home/webadmin/dev.taracares.com/dev/lib/python3.8/site-packages/selenium/webdriver/remote/webelement.py", line 710, in _execute return self._parent.execute(command, params) File "/home/webadmin/dev.taracares.com/dev/lib/python3.8/site-packages/selenium/webdriver/remote/webdriver.py", line 423, in execute response = self.command_executor.execute(driver_command, params) File "/home/webadmin/dev.taracares.com/dev/lib/python3.8/site-packages/selenium/webdriver/remote/remote_connection.py", line 333, in execute return self._request(command_info[0], url, body=data) File "/home/webadmin/dev.taracares.com/dev/lib/python3.8/site-packages/selenium/webdriver/remote/remote_connection.py", line 355, in _request resp = self._conn.request(method, url, body=body, headers=headers) File "/home/webadmin/dev.taracares.com/dev/lib/python3.8/site-packages/urllib3/request.py", line 74, in request return self.request_encode_url( File "/home/webadmin/dev.taracares.com/dev/lib/python3.8/site-packages/urllib3/request.py", line 96, in request_encode_url return self.urlopen(method, url, **extra_kw) File "/home/webadmin/dev.taracares.com/dev/lib/python3.8/site-packages/urllib3/poolmanager.py", line 375, in urlopen response = conn.urlopen(method, u.request_uri, **kw) File "/home/webadmin/dev.taracares.com/dev/lib/python3.8/site-packages/urllib3/connectionpool.py", line 783, in urlopen return self.urlopen( File "/home/webadmin/dev.taracares.com/dev/lib/python3.8/site-packages/urllib3/connectionpool.py", line 783, in urlopen return self.urlopen( File "/home/webadmin/dev.taracares.com/dev/lib/python3.8/site-packages/urllib3/connectionpool.py", line 783, in urlopen return self.urlopen( File "/home/webadmin/dev.taracares.com/dev/lib/python3.8/site-packages/urllib3/connectionpool.py", line 755, in urlopen retries = retries.increment( File "/home/webadmin/dev.taracares.com/dev/lib/python3.8/site-packages/urllib3/util/retry.py", line 574, in increment raise MaxRetryError(_pool, url, error or ResponseError(cause)) urllib3.exceptions.MaxRetryError: HTTPConnectionPool(host='localhost', port=58331): Max retries exceeded with url: /session/0f8192d1-c39f-49d1-9a99-7f91dfe95481/element/a5dd2645-6c15-44dc-b000-04bf6b7ea6cb/text (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7fd9dcde24f0>: Failed to establish a new connection: [Errno 111] Connection refused')) This is code being run in tests for a django application. The tests used to run fine, now the last 4 tests (which use selenium) have errors, which started after I added driver.quit() after each test. … -
Accessing User objects through User.objects.filter for a profile page
I have a model called Question and Answer How can i get user information like username, email, first name, last name and the Question model into his profile. I want to display all these information in his profile page. the question model class Question(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=100, blank=False, null=False) body = RichTextField(blank=False, null=False) category = models.CharField(max_length=50, blank=False, null=False) def __str__(self): return str(self.title) as you can see here in the Profle view i'm willing to access user email, but how can i query the database to get all these information in the profile page ? def profile(request, pk): user_profile = User.objects.filter(email=request.user) context = {'user_profile':user_profile} return render(request, 'profile.html', context) the profile template: {{user.email}} <div class="container"> <div class="row justify-content-center"> {% for question in list_of_question reversed %} <div class="col-md-4"> <div class="card my-3"> <div class="card-header"> <p class="card-title">{{question.user.username.upper}}</p> </div> <div class="card-body"> <a href="{% url 'view-Question' question.id %}" style="text-decoration: none;"> <p class="card-title">{{question.title}}</p> </a> <p>Category: {{question.category}}</p> </div> </div> </div> {%endfor%} </div> </div> -
How to automatically set ManyToMany relationship with user
How to automatically set owner field with the user which creates this event? Event model: class Event(models.Model): title = models.CharField(max_length=50, unique=True) describe = models.TextField(max_length=500) type_of_event = models.IntegerField(choices=TYPE_OF_EVENT_CHOICE, default=0) img = models.ImageField(null=True, blank=True) owner = models.ForeignKey(User, on_delete=models.CASCADE) event_date = models.DateTimeField() city = models.ForeignKey(City, verbose_name='City', on_delete=models.CASCADE) address = models.CharField(max_length=60) ticket_price = models.IntegerField(default=0) email = models.EmailField(max_length=100, verbose_name='Contact email', validators=[validate_email]) Event`s view: class CreateEventView(generics.CreateAPIView): serializer_class = EventDetailSerializer permission_classes = [IsAuthenticated] Event`s serializer: class EventDetailSerializer(serializers.ModelSerializer): class Meta: model = Event fields = ['title', 'img', 'type_of_event', 'describe', 'event_date', 'city', 'address', 'ticket_price', 'email'] -
How do I re-use <option> data in HTML forms? (Django) (DRY)
I'm generating an HTML response via Django with a large set of forms, and one of the form fields is a <select> with many (1,000+) <option>s in the queryset. Due to repeating the <option>s for each form, the HTML response is egregiously long. I've used pagination to reduce the amount of HTML rendered in each response, but this isn't optimal for the particular application. Is it possible to render the <option>s once on the HTML response and reference it in each form field without rendering it again? -
How to access the submitted value of a django form?
I am trying to make an e-commerce site that allows the user to place bids through a form. The new bid that the user posts has to be larger than the listing price on the listing and any other bids. I need help accessing the value that the user submits to check if it meets the previously stated requirements. views.py def listing(request, id): #gets listing listing = Listings.objects.get(id=id) #code for forms listing_price = listing.bid comment_obj = Comments.objects.filter(listing=listing) form = CommentForm() bid_form = BidsForm() if request.method == "POST": form = CommentForm(request.POST) bid_form = BidsForm(request.POST) new_bid = bid_form.cleaned_data.get('newBid') if form.is_valid(): comment = form.save(commit=False) comment.listing = listing comment.user = request.user comment.save() if (bid_form.is_valid()) and (new_bid >= listing_price): bid = form.save(commit=False) bid.listing = listing bid.user = request.user bid.save() else: return render(request, "auctions/listing.html",{ "auction_listing": listing, "form": form, "comments": comment_obj, "bidForm": bid_form }) return render(request, "auctions/listing.html",{ "auction_listing": listing, "form": form, "comments": comment_obj, "bidForm": bid_form }) (There are two forms, one for comments and one for bids.) html <!--bid form--> <form action = "{% url 'listing' auction_listing.id %}" method = "POST" name = "newBid"> {% csrf_token %} {{ bidForm }} <input type = "submit" value = "Place Bid"> </form> -
Convert a list of dictionaries to a dictionary of dictionaries
I have a list of dictionaries in python3, that form a pyramid-type structure of 5 levels top, and i need to convert to a dictionary of dictionary in base to one value. for example the list: [{"name":"exampleName2", "referal":"exampleName1", "data":"data"}, {"name":"exampleName3", "referal":"exampleName2", "data":"data"}, {"name":"exampleName4", "referal":"exampleName3", "data":"data"}] need to be converted to: {"name:"exampleName1", "refered":[{"name:"exampleName2", "refered":[{"name:"exampleName3", "refered":[{"name:"exampleName4", "refered":[], "data":"data}], "data":"data}], "data":"data}], "data":"data} I could do a lot of for and while loops, but i think there is a fast method. My method at the moment is: try: porOrdenar = LISTADO ordenados = [] while len(porOrdernar) > 0: n = 0 while n < len(porOrdernar): if porOrdernar[n]["referal"]=="uno": ordenados.append(porOrdernar[n]) porOrdernar.pop(n) for element in ordenados: unirReferidos(porOrdernar, n, element1) for element1 in element["referidos"]: unirReferidos(porOrdernar, n, element1) for element2 in element1["referidos"]: unirReferidos(porOrdernar, n, element2) for element3 in element2["referidos"]: unirReferidos(porOrdernar, n, element3) n +=1 except IndexError: pass def unirReferidos(porOrdernar, n, element3): if porOrdernar[n]["referal"] == element3["name"]: element3["refered"].append(porOrdernar[n]) porOrdernar.pop(n) -
CSS not applying to html
I'm trying to attach a CSS file to my HTML files, but when I run the server on localhost the CSS isn't being applied. I have gone through quite a bit of troubleshooting but every time I end up just having to put the styling I want straight into the HTML document as it won't apply if left in the CSS document and linked through via class="". style.css: .remove-default-btn { background-color: transparent; border: none; box-shadow: none; } .edit-color { color: #333 } .post-link { text-decoration: none; } .post-text { padding-top: 0.5rem; } .post-img { float: left; margin-right: 1rem; } .child-comment { margin-left: 2rem; } .notification-badge { transition: 0.3s; } .notification-badge:hover { cursor: pointer; opacity: 0.75; transition: 0.3s; } .dropdown { position: relative; display: inline-block; } .dropdown-content { position: absolute; background-color: #f1f1f1; min-width: 350px; box-shadow: 0px 8px 8px 0px rgba(0,0,0,0.2); z-index: 1; font-size: 0.9rem; } .dropdown-content a { color: black; padding: 12px 16px; text-decoration: none; display: block; } .dropdown-content a:hover { background-color: #ddd; } .dropdown-item-parent { position: relative; display: block; } .dropdown-item-close { position: absolute; top: 0; right: 0; font-size: 1.8rem; padding-right: 5px; transition: 0.3s; } .dropdown-item-close:hover { color: rgb(180, 25, 25); transition: 0.3s; cursor: pointer; } show_notifications.html: <div class="dropdown"> <span … -
docker container for Django hangs when updating mounting sources
As part of a course I am currently passing there is a situation when following combination is used: A docker container is created for very standard scenario: One for Django, second one for Postgresql database and then a compose file is managing all this stuff. And the sources are actually mounted using the docker-compose volumes. The entire application I created during the course is available in my github: https://github.com/arsenhakobyan/recipe-app-api The problem I faced is with running django test command each time when I update any source file. steps to reproduce the issue I have: build images with docker-compose build run the following command: docker-compose run --rm app sh -c "python manage.py test" The process should run as expected. Edit any file (e.g. app->user->tests->test_user_api.py) and save the changes run the command from step 2. the process hangs at this point in my case and I can not even force to remove the docker containers, even tried to deactivate some endpoints from the network that is connected with that containers (I think that could help when I read some of the error messages). The only way to continue work is to restart the docker exe on my machine. Let me know if … -
How to connect two databases in django for local and remote servers?
guys. I have a database, which I deployed on Heroku. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'd7mj3h2mco40v9', 'USER': 'fwla1qyxgxrrqk', 'PASSWORD': get_secret('DB_PASSWORD'), 'HOST': 'ec2-54-174-73-136.compute-1.amazonaws.com', 'PORT': '5432', } } The problem is when I add comments objects on a local machine, they automatically downloaded to the remote database. It's not convenient. I want to create, for example, a local database which will save all migrations or changes of my models, but not downloaded into a remote server. And when I need to download the data, I will do something and the changes are to appear on a remote database. What do I need to do for this? How to make the right migrations and then work with them? I'm newbie, please don't advice complicated things I can't understand :) -
is there any way in django to list all devices a user logged in?
I am trying to list all the device and their locations on which a user account is logged in . similar to login activity of instagram, is there any way to do this? sorry for my bad english 😅 -
django rest upload multiple images
I'm working on an e-commerce API with Django rest framework so I want when the user adds a new product he can upload multiple images how can I do that with rest framework? here are my models, views, serializer my models.py class Product(models.Model): title = models.CharField(max_length=255) slug = models.SlugField() description = models.TextField(null=True, blank=True) owner = models.ForeignKey(User, related_name='Products', on_delete=models.CASCADE,null=True) class ProductImages(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='images') images = models.FileField(upload_to='API/images',max_length=100,null=True) my serializer class ProductImageSerializer(serializers.ModelSerializer): class Meta: model = ProductImages fields = '__all__' class Productserializer(serializers.ModelSerializer) : images= ProductImageSerializer(many=True) class Meta: model = Product fields = ('id','title','price','description','whatfor','categories','size','rooms','Location','Lat','Long','owner_id','images') extra_kwargs = {"user":{"read_only":True}} def validate(self, attrs): attrs['owner'] = self.context.get("request").user return attrs my views class ProductViewSet(ModelViewSet): queryset = Product.objects.all() serializer_class = Productserializer filter_backends = [DjangoFilterBackend, SearchFilter, OrderingFilter] filterset_class = ProductFilter search_fields = ['title', 'description'] ordering_fields = ['price', 'last_update'] def get_serializer_context(self): return {'request': self.request} -
csrf_exempt is not working in my django project
I am using django 3.2 I am trying to use a twilio webhook on my site but still getting the error 403 forbidden <p>CSRF verification failed. Request aborted.</p> <p>You are seeing this message because this site requires a CSRF cookie when submitting forms. This cookie is required for security reasons, to ensure that your browser is not being hijacked by third parties.</p> <p>If you have configured your browser to disable cookies, please re-enable them, at least for this site, or for “same-origin” requests.</p> my view @csrf_exempt @validate_twilio_request def webhook(request): return HttpResponse("something") what are my doing wrong? -
Why does a Django foreign key id __in query fail to match None?
When filtering a queryset on a nullable foreign key, I can filter by an ID value (foo_id=123) or by None (foo_id=None). However, if I attempt to filter by a list (foo_id__in=[123, None]) the None is ignored. Why is this happening, and what is the best workaround for filtering on a foreign key using a list which includes None? Example: from django.db import models class Foo(models.Model): name = models.CharField(max_length=100) class Bar(models.Model): foo = models.ForeignKey(Foo, on_delete=models.PROTECT, blank=True, null=True) foo = Foo.objects.create(name='myfoo') Bar.objects.create(foo=foo) Bar.objects.create(foo=None) Bar.objects.count() # 2 Bar.objects.filter(foo_id=foo.id).count() # 1 Bar.objects.filter(foo_id=None).count() # 1 Bar.objects.filter(foo_id__in=[foo.id, None]).count() # 1 - Expected 2! -
how can i use django comment_set.all
My problem Make comment model, and form for Django Use {% for i in post.comment_set.all %} no change html Information saved in the comment form does not appear how can i fix it? MY top_detail.html <form method="POST" action="{% url 'create_comment' post.id %}"> {% csrf_token %} {{ comment_form }} <input type="submit"> {% for i in post.comment_set.all %} <p>comment: {{ i.subject }}</p> <p>time: {{ i.created_at }}</p> <hr> {% endfor %} </form> MY models.py from django.db import models class Top(models.Model): product_name = models.CharField(blank=True, null=True, max_length=30) product_price = models.CharField(blank=True, null=True, max_length=30) product_image = models.ImageField(blank=True, null=True, upload_to="images") product_explain = models.TextField(blank=True, null=True, ) class Question(models.Model): post = models.ForeignKey(Top, null=True, on_delete=models.CASCADE) subject = models.CharField(null=True, max_length=150) created_at = models.DateTimeField(auto_now=True) def __str__(self): return self.subject MY urls.py from django.urls import path from django.contrib.auth import views as auth_views from . import views from .views import PostList urlpatterns = [ path('home/', views.home, name='home'), path('home/top', PostList.as_view(), name='top'), path('home/top/<int:pk>/', views.top_detail, name='top_detail'), path('search/', views.search, name='search'), path('signup/', views.signup, name='signup'), path('login/', auth_views.LoginView.as_view(template_name='main/login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(), name='logout'), path('create_comment/<int:post_id>', views.create_comment, name='create_comment'), ] My views.py def top_detail(request,pk): post = get_object_or_404(Top, pk=pk) post_list = Top.objects.get(pk=pk) comment_form = CommentForm() return render(request, 'main/top_detail.html', {'post':post, 'post_list':post_list,'comment_form':comment_form}) def create_comment(request, post_id): filled_form = CommentForm(request.POST) if filled_form.is_valid(): form = filled_form.save(commit=False) form.post = Top.objects.get(id=post_id) form.save() return redirect('top_detail',post_id) MY … -
'>' not supported between instances of 'NoneType' and 'NoneType' Overlapping Check
Hi I am getting this error in my validation check def sefl(clean): start_number=self.cleaned_data.get("start_number",None) end_number=self.cleaned_data.get("end_number",None) latest_start=max(start_number, end_number) earliest_end = min(start_number, end_bbch) delta = (earliest_end - latest_start) + 1 if delta is None: raise ValidationError("overlap not allowed") -
PylancereportMissingModuleSource on VS Code
I have the following code from a tutorial which I am following: from django.http import HttpResponse import random from django.template.loader import render_to_string from articles.models import Article The issue is that I am getting this error in VS Code: Import "django.http" could not be resolved from sourcePylancereportMissingModuleSource Import "django.template.loader" could not be resolved from sourcePylancereportMissingModuleSource It is odd because on the terminal in vs code if I type the import commands, it is not producing any error. So since the webpage is producing DoNotExist error, i am not sure if this is because of these packages or because of some other factor. I did try to find out if i was using a different interpreter than the django virtual environment import sys print(sys.executable) Produces the location of the virtual environment for this project so it is the right interpreter. -
Django update table on page every 5 sec
So i have a template which gets a list of lists with information for table. I render data like that way Here is my template html {% for each in info %} <tr class="bg-dark-2"> <th data-label="Seller" scope="row"><span class="fw-bold">{{ each.2 }}</span></th> <th data-label="U give"> <div class="d-flex align-items-center"> <span class="icon d-flex align-items-center justify-content-center me-3"></span><span>{{ each.4}}</span><span class="fw-normal ms-3">{{ each.0 }}</span> </div> </th> <th data-label="U get"><span>{{ each.1 }} {{ each.5 }}</span></th> <th data-label="Limit"><span>from {{ each.8 }} to {{ each.9 }}</span></th> <th data-label="Reserve"><span>{{ each.6 }}</span></th> <th data-label=""> <a class="btn btn-success btn-block" href="{{ each.3 }}">Buy</a> </th> </tr> {% endfor %} So the task is, how can i update data on my django webpage, without refreshing it? (every 5-10 seconds) Or how can i use ajax for delete table and download new data to it? -
how to save file location to database sqlite3 - django
i want to save file location to database sqlite3, but the file just save it to local storage. i tried to make it but there's error : here's my models : from django.db import models from django.core.files.storage import FileSystemStorage fs = FileSystemStorage(location='/media/mp3') class Audio_store(models.Model): record=models.FileField(storage=fs) forms.py : from django import forms from .models import Audio_store class AudioForm(forms.ModelForm): class Meta: model = Audio_store fields= ['record'] views.py : def homepage(request): form = AudioForm() audio = Audio_store.objects.all() if request.method == "POST": form = AudioForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect("homepage") context={'form':form, 'audio':audio} return render(request, "homepage.html", context=context) please help me to fix it -
Django: To get all child and grandchild objects recursively
There is a model called Comment with the following recursive relationship. class Comment(models.Model): video = models.ForeignKey(ProductVideo, on_delete=models.CASCADE) text = models.TextField(max_length=1000) commented_at = models.DateTimeField(default=timezone.now) parent = models.ForeignKey( "self", blank=True, null=True, on_delete=models.CASCADE, related_name="replies", ) def __str__(self): return f"{self.user}, {self.text[:10]}" And the children of the parent comment A are B, C, D... and there are multiple layers of recursive relations. . └── A ├── B │ └── C ├── D │ └── E │ └── F ├── G └── H └── I └── J └── K How can I get all these children from an object called A efficiently and with a flat result? // Comment.objects.get(pk="A") [ {"id": "A"}, {"id": "B"}, {"id": "C"}, {"id": "D"}, {"id": "E"}, {"id": "F"}, {"id": "G"}, {"id": "H"}, {"id": "I"}, {"id": "J"}, {"id": "K"}, ] There are various django-mptt, django-cte, etc. What should we use? -
Error when listing out a user's followers
I am trying to add a notifications feature to my social media platform. Part of this involves adding a notifications logo to my navbar at the top of my website which will display the number of unseen notifications a logged-in user has. When I run my server, I receive a NameError: NameError Here is part of my navbar.html: {% load custom_tags %} (...) {% if user.is_authenticated %} <div class="nav-item dropdown"> <a class="nav-link dropdown-toggle text-dark" data-bs-toggle="dropdown" href="#" role="button" aria-expanded="false"><i class="fas fa-user"></i></a> <ul class="dropdown-menu dropdown-menu-end"> <li><a class="dropdown-item" href="{% url 'profile' request.user.profile.pk %}">Profile</a></li> <li><a class="dropdown-item" href="{% url 'account_logout' %}">Sign Out</a></li> </ul> </div> <div class="nav-item"> {% show_notifications %} {% endif %} </div> </div> </nav> Here is my show_notifications.html: <div class="dropdown"> <span class="badge bg-primary notification-badge">{{ notifications.count }}</span> <div class="dropdown-content d-none" id="notification-container"> {% for notification in notifications %} {% if notification.post %} {% if notification.notification_type == 1 %} <div class="dropdown-item-parent"> <a href="#">@{{ notification.from_user }} liked your post</a> <span class="dropdown-item-close">&times;</span> </div> {% elif notification.notification_type == 2 %} <div class="dropdown-item-parent"> <a href="#">@{{ notification.from_user }} commented on your post</a> <span class="dropdown-item-close">&times;</span> </div> {% endif %} {% elif notification.comment %} {% if notification.notification_type == 1 %} <div class="dropdown-item-parent"> <a href="#">@{{ notification.from_user }} liked on your comment</a> <span class="dropdown-item-close">&times;</span> </div> {% … -
column contains null values
I added Person as a foreign key to the CareerHistory table. person = models.ForeignKey( Person, on_delete=models.PROTECT, default=None, related_name='careerist') I set default=None thinking this would avoid that error when running migrations about making a new field on an existing table without a default value. However, instead I got django.db.utils.IntegrityError: column "person_id" contains null values Now, there are only 114 Persons in that table, and all of them have ids, so I find this error very confusing. I looked at this answer: SQL Django Null Constraint Error - cannot resolve? and decided to try: person = models.ForeignKey( Person, on_delete=models.PROTECT, default='', related_name='careerist') However, this still came back with the same error. Then I went to: person = models.ForeignKey( Person, on_delete=models.PROTECT, default='', null=True, related_name='careerist') But I still get the same error. I don't understand what is happening here. Can someone please explain, and show me how to fix this? I don't want to just fix it, I want to understand what is happening here. Maybe I need to edit my migrations file(s)? Thanks. -
Duplicate the data OR saving Order Items data into JSONField
I have one to many Relationship with Order to OrderItem. OrderItems is saving the details of Item table. Item can be deleted by user, but I cannot delete the information of an item from OrderItem table ( Because it will used for Generating reports), so that is why I did not move the Item key to OrderItem and saving all the information of item table to OrderItem. Now you can see that, data is being duplicated from Item to OrderItem table. My question is or I want to ask for suggestions that, i am using postgresql and we have luxury of JSONField. So is it a good idea to save all the information of Item table into JSONField and remove all fields? Later on I have to generate reports from OrderItem, like how many Orders has been placed or calculate the profit using OrderItem table. class Item(models.Model): class Meta: db_table = 'items' SKU = models.PositiveIntegerField() name = models.CharField(max_length=255, blank=False, null=False) supplier = models.ForeignKey(Supplier,on_delete=models.CASCADE, blank=False, null=False) purchase_price = models.DecimalField(max_digits=10, decimal_places=2) trade_price = models.DecimalField(max_digits=10, decimal_places=2,blank=False, null=False , default = 0.00) retail_price = models.DecimalField(max_digits=10, decimal_places=2) class Order(models.Model): class Meta: db_table = 'orders' customer = models.ForeignKey(Customer, on_delete=models.CASCADE, null=True, related_name='orders') serial_no = models.CharField(max_length=30, null=False, unique=True) … -
Django Annotate resolve diferent value than bucle for in one Subquery
I have this Query with Annotate: whateverquery=Whatever.objects.filter(query,important_field__isnull=False).values('important_field','id').annotate( total=Count('id'), total_contract_by_user=Count( Subquery(OtherWhatever.objects.filter( whatever__important_field=OuterRef('important_field'), status="asignada", visibility=True, confirm=True).values('user').distinct(),output_field=IntegerField())) ).values('total','total_contract' ).annotate(tasa_conversion=Cast(F('total_contract_by_user')/F('total'),FloatField()) ).values('total','total_contract','tasa_conversion' ).order_by(order) It not resolve the same value in total_contract_by_user that: for w in whateverquery: total_contract_by_user = OtherWhatever.objects.filter(visibility=True,confirm=True,status="asignada",Whatever__important_field=w['important_field']).values('user').distinct() tasa_conversion = round((total_contract_by_user.count() / int(w['total']))*100,2) I do not know what I have wrong in Annotate in Query.