Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Joining and grouping Django querysets
m1 = myModel.objects.filter(...) m2 = myModel.objects.filter(...) n1 = m1.values("date").annotate(car_crashes=Sum('car_crashes') * 1).values("date", "car_crashes") n2 = m2.values("date").annotate(car_crashes=Sum('car_crashes') * 2).values("date", "car_crashes") With this code, I get in n1 and n2 two querysets: <QuerySet [{'date': datetime.date(2008, 4, 1), 'car_crashes': Decimal(1.000)}, ... ]> <QuerySet [{'date': datetime.date(2011, 4, 1), 'car_crashes': Decimal(2.000)}, ... ]> Please note that they might not be of the same size and some dates might be in one queryset but not the other. How can I group these 2 querysets on the date field and sum car_crashes? -
Storing hierarchies/trees insdie a django model field?
First off, I know that there are packages like django-mptt and django-treebeard, but these don't look like what I am looking for. (There the goal seems to be to arrange all the model instances in a tree and the model has fields that encode the position of each instance. There is only one tree, nodes can be rearranged, deleted, or newly inserted.) The task: My goal, roughly speaking, is to have a model that stores trees. There are multiple trees to store in the database, and each instance of the model stores one of those trees. I'll try to illustrate two different usage examples of different complexity. The first is probably easy to implement, the second... I don't know. [Side question: Is there a name for what I am looking for? Searching for django+tree results in discussions of problems and solutions that are like django-mptt...] Simple case: Consider models for chapters and books. class Chapter(Model): heading = CharField() text = TextField() class Book(Model): name = CharField() structure = ???magic??? The chapter model stores the text parts of the book, so you'd have one instance holding heading and text on Topic A, another for Topic B, and so on. The book … -
Django: How to know the raw sql and the time taken by a model queryset
I am trying to know the 1) time taken or duration and 2) raw sql for any django model queryset Eg: users = User.objects.all() print(time_take for users) print(raw sql of users) -
Django not showing database updates
I have a django template that just lists out a postgresql table: <table> {% for prod in object_list %} <tr> <td><a href='{% url 'prod-detail' pk=prod.prod_id %}'>{{prod.prod}}</a></td> <td>{{prod.title}}</td> <td>{{prod.rank}}</td> <td>{{prod.date}}</td> <td>{{prod.error}}</td> </tr> {% endfor %} </table> The table was working fine until I decided to try testing what would happen if prod.title didn't exist. I went into PGAdmin and changed the title field to null on three of the products. When I reloaded the page, those fields still showed the data that I had removed. I am running postgresql 11.4, Python 3.73, and Django 2 on a Windows 10 Pro laptop. I tried stopping and restarting the Django server. The data persists. PGAdmin definitely shows the fields as null. I've searched for this issue, but I haven't come up with any answers. The Django documentation indicates that unless set otherwise connections don't persist... The code above is all I've tried. It continues to work fine, but it never reflects the updates that I've made to the database. I was expecting those fields to show as empty in my html table, but they still show the data that I removed. Thanks for any suggestions. --Al -
EB CLI - 403 when creating environment
I am brand new to ElasticBeanstalk, so any verbosity you can offer to help me understand what I'm doing wrong is greatly appreciated. I am getting the following 403 Forbidden Error within EB CLI when running eb create: ERROR: CommandError - An error occurred while handling git command. Error code: 128 Error: fatal: unable to access 'https://git-codecommit.us-east-2.amazonaws.com/v1/repos/origin/': The requested URL returned error: 403 My IAM User has the following permissions: AWSElasticBeanstalkFullAccess AWSCodeCommitFullAccess I've searched for any others that may be relevant, but couldn't find any obvious ones. My application is a Django app with the following file structure: streambeacon |_ .elasticbeanstalk |_ config.yaml |_ .venv |_ streambeacon-api *(django parent)* |_ application *(django app)* |_ payment *(django app)* |_ scripts *(django app)* |_ streambeacon *(django config)* |_ settings.py ** folder structure for reference, not complete. .elasticbeanstalk/config.yaml branch-defaults: master: environment: null group_suffix: null global: application_name: streambeacon-api branch: master default_ec2_keyname: xxxx-ommitted--xxxx default_platform: Python 3.4 default_region: us-east-2 include_git_submodules: true instance_profile: null platform_name: null platform_version: null profile: eb-cli repository: origin sc: git workspace_type: Application I have read in another SO question that the issue for them was that port 443 wasn't exposed in their security group, but I am creating this environment via CLI & … -
shopping cart not save item using django session
I am not sure why django return an empty shopping cart when trying to use session. Using pdb i can see that the data are sent to the template but something is wrong somewhere. Before using session and while hardcoding without session i was able to make it work. I need assistance, please. view.py def cart(request): """ List of items in cart with session. """ try: the_id = request.session['cart_id'] except: the_id = None if the_id: cart = Cart.objects.get(id=the_id) context = {"cart": cart} else: empty_message = "Your cart is empty, please keep shopping." context = {"empty": True, "empty_message": empty_message } return render(request, 'carts/cart.html', context) def update_cart(request, slug): """ Add items to cart with session. """ try: the_id = request.session['cart_id'] except: new_cart = Cart() new_cart.save() request.session['cart_id'] = new_cart.id the_id = new_cart.id cart = Cart.objects.get(id=the_id) try: product = Product.objects.get(slug=slug) except Product.DoesNotExist: pass except: pass if not product in cart.products.all(): cart.products.add(product) else: cart.products.remove(product) new_total = 0.00 for item in cart.products.all(): new_total += float(item.price) cart.total = new_total cart.save() return HttpResponseRedirect(reverse('carts:cart')) cart.html {% block content %} <div class="col-sm-8 col-sm-offset-2 mt-5 ml-5"> <div class="d-flex justify-content-between"> <h3 class="header mb-4">Cart</h3> <a href='{% url "products:list" %}'> <h5 class="card-title">List of Products</h5></a> </div> {% if empty %} <h4 style="text-align:center;">{{ empty_message }}</h4> {% … -
Django app on AWS EC2 not returning data for specific computers
My Django server does not return data from the AWS RDS database for some users. I have a Django server deployed to an AWS EC2 instance and setup using Nginx and Uwsgi. I am using an AWS RDS PostgreSQL database to store my data for the same. Every time the front end makes a request to the server, the server reads some data from the database and returns it as a JSON object. It works fine for me. However, some users have reported no data being revealed for them on the front-end. So, I tried logging the results of the API call, and I found that for the same request, the request from my computer gets some data, while from some other user's computer - the retrieved data object is empty. (Note: The user has 40Mbps internet speed, so it's not a speed issue per say) I thought it might be an issue with RDS, so I tried migrating to a different database, but that didn't fix it either. I also tried changing the instance region, but that didn't affect anything either. -
Custom User model error: AttributeError: 'CustomUser' object has no attribute 'is_anonymous'
Trying to set up a custom user model that extends the base user. Some user will have login information and some will not, but I still want all users logged. That's what I think the error is saying. In the default Django model they were logged, but now some users will just have just IP address and username. Other users will have more information like email, etc. Gettin this error: AttributeError: 'CustomUser' object has no attribute 'is_anonymous' Here is my custom user class: class MyUserManager(BaseUserManager): def create_user(first_name, last_name, address1, state, zipcode, email, username, password): user=self.model( first_name = first_name, last_name = last_name, address1 = address1, zipcode = zipcode, state = state, email=email, username = username, password = password ) user.is_superuser = False user.is_admin = False user.is_staff = False user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(email, password, **extra_fields) class CustomUser(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=25 ) last_name = models.CharField(max_length=25 ) address1 = models.CharField(null=True, max_length=100, blank=True) zipcode = models.CharField(max_length=10, null=True,blank=True) state = models.CharField(null=True, max_length=2, blank=True) email = models.EmailField(max_length = 250) username = models.CharField(max_length = … -
Adding fonts to django-summernote
I'd like to add some Google fonts to django-summernote as selectable fonts. I've loaded the font within the html file. I know that I'm doing this correct as the the rest of the text on the page uses this font (i.e. Questrial) I then go into my settings file and add Questrial to the 'fontname' line SETTINGS_DEFAULT = { 'iframe': True, 'airMode': False, 'empty': ('<p><br/></p>', '<p><br></p>'), 'width': 720, 'height': 480, 'toolbar': [ ['style', ['style']], ['font', ['bold', 'italic', 'underline', 'superscript', 'subscript', 'strikethrough', 'clear']], ['fontname', ['fontname', 'Questrial']], ['fontsize', ['fontsize']], ['color', ['color']], ['para', ['ul', 'ol', 'paragraph']], ['height', ['height']], ['table', ['table']], ['insert', ['link', 'picture', 'video', 'hr']], ['view', ['fullscreen', 'codeview']], ['help', ['help']], ], Even with this change, I don't have the ability to select the Questrial font in the summernote widget. Any help would be appreciated. Thanks! -
how to fix a static file heroku hosting problem and database
I am deploying my site in production in Heroku my I have static file issues and database Application error An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details. You can do this from the Heroku CLI with the command heroku logs --tail at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" and init.py:144: UserWarning: The psycopg2 wheel package will be renamed from release 2.8; in order to keep installing from binary please use "pip install psycopg2-binary" instead. For details see: I thought I put "procfile" in the wrong place actually no, it's the same level as manage. py -
How do I access POST Data in Django, "No connection adapters were found for '<QueryDict: {}>'"
Hi I was wondering why I can't access the data I submitted in a form in another view. Django keeps telling me "No connection adapters were found for ''" Here's my html: <div class="modal-body"> <form method="post"> {% csrf_token %} <div class="form-group"> <label for="recipient-name" class="col-form-label">Link</label> <input type="text" class="form-control" id="recipient-name"> </div> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <a href={% url 'post-parse' %}> <button class="btn btn-info" type="submit">Submit</button> </a> </div> Here's my view.py: class PostParseView(PostCreateView): def get_initial(self): # Get the initial dictionary from the superclass method initial = super(PostParseView, self).get_initial() initial = initial.copy() recipe = AbstractParser(self.request.POST) ... ... My problem is the method self.request.POST doesn't work for me, I tested with different url's and my code works, but I can't access the url I submitted. If I replace self.request.POST with any url I want the code works, can anyone help me identify what I can do to make post work properly? Thank you!! -
Django + Nginx on subdomain Bad request 400
I need to deploy app to prod to subdomain. DNS A-record of app.mysite.com have value of machine. A-record of mysite.com have ip of different computer. Stack: Nginx, Django, Gunicorn. Nginx works fine on IP, but invokes 400 on subdomain. I've tried adding proxy_set_header values proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; but it doesn't help. nginx/sites-enabled/mysite: (If I change server_name ti IP it wirks fine) server { listen 80; server_name app.mysite.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/user/mysite; } location / { proxy_set_header Host $host; include proxy_params; proxy_pass http://unix:/home/user/mysite.sock; } } settings.py ALLOWED_HOSTS = [ip of machine,'127.0.0.1', 'app.mysite.com','mysite.com'] I want app to work only at subdomain. How could I achieve it? Possibly helpful last Nginx process logs Aug 10 21:23:59 my-machine systemd[1]: Starting A high performance web server and a reverse proxy server... Aug 10 21:23:59 my-machine systemd[1]: nginx.service: Failed to parse PID from file /run/nginx.pid: Invalid argument Aug 10 21:23:59 my-machine systemd[1]: Started A high performance web server and a reverse proxy server. Aug 10 21:25:09 my-machine systemd[1]: Stopping A high performance web server and a reverse proxy server... Aug 10 21:25:09 my-machine systemd[1]: Stopped A high performance web server … -
How to execute python manage.py django management command via button on the website on Heroku
I have a Django management commands that I would like to run. I would like to have it available for a user by clicking the button and it would execute it. I do not need help to write one - I have them working, but always I need to run them from the terminal like: heroku run python manage.py syncdata Very convenient would be to just click the button on the running production website and it would start it for me. How can I make this happen on the site running on Heroku? -
Customizing django-allauth password_reset_from_key template
I'm using django 2.2.3, I'm overriding django-allauth templates and on password_reset_from_key template I came across a NoReverseMatch Exception, Reverse for 'account_reset_password_from_key' with no arguments not found. 1 pattern(s) tried: ['accounts/password/reset/key/(?P<uidb36>[0-9A-Za-z]+)-(?P<key>.+)/$'] So it expects argument and probably that argument is the key that is generated during resetting password. From the URL pattern, 'key' is the variable's name I tried to pass it with 'key'. <form method="POST" action="{% url 'account_reset_password_from_key' key %}"> ... </form> but it did not work. What is wrong? -
DisallowedHost at Invalid HTTP_HOST header during add custom domain
Getting error after adding domain name in django project http://digitalrajat.in/ IP address working perfectly http://134.209.153.233/ Serice Provider Dgitalocean Server UBUNTU Apache2 DisallowedHost at / Invalid HTTP_HOST header: 'digitalrajat.in'. You may need to add 'digitalrajat.in' to ALLOWED_HOSTS. -
How to rename only some items in values() in Django?
Like the title says I need to rename some items in a queryset. The code for the queryset is made like this: data = SnpsFunctionalelement.objects.values('snpid__rsid', 'elementid__name', 'celllineid__name', 'countexperiments', 'filetype') i tried to rename the values using from django.db.models import F but if I do data = SnpsFunctionalelement.objects.values(rsid=F('snpid__rsid'), FunctionalElement=F('elementid__name'), CellLine=F('celllineid__name'), countexperiments=F('countexperiments'), filetype=F('filetype')) it gives me an error because countexperiments and filetype are already the names assigned to the model to which they belong. So is there a way to rename only a part of the values of the queryset mantaining the remaining ones? -
How to not allow the ModelSerializer update method?
I'm building an API and there's a route that I don't want it to be available for updates. I tried to override the ModelSerializer's update() method, but I'm having some problems with the nested relationship This is the serializer code. The last_location and the inventory are nested relationship. class SurvivorSerializer(ModelSerializer): last_location = LocationSerializer(many=False) inventory = InventorySerializer(many=False) class Meta: model = Survivor fields = '__all__' def update(self, instance, validated_data): return Response({"Error": "Not allowed"}, status=HTTP_405_METHOD_NOT_ALLOWED) When I try to update I get this message: Got AttributeError when attempting to get a value for field `last_location` on serializer `SurvivorSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `Response` instance. Original exception text was: 'Response' object has no attribute 'last_location'. -
Django looking in wrong directory for templates
I followed a tutorial that taught to structure your templates directory as follows ~/project/main/templates/main to avoid and confusion. Now I'm trying to create another project and use the same structure as good practice. I get a TemplateDoesNotExist error when trying to render html located at /home/arch/project/main/templates/main/index.html it says Django is looking in /home/arch/project/templates/main/index.html settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'templates') ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] main/views.py from django.shortcuts import render, redirect def homepage_view(request): return render(request, "main/index.html") main/urls.py from django.urls import path from . import views app_name = "main" urlpatterns = [ path("", views.homepage_view, name="homepage_view") ] structure of my project . ├── db.sqlite3 ├── main │ ├── admin.py │ ├── apps.py │ ├── __init__.py │ ├── migrations │ │ └── __init__.py │ ├── models.py │ ├── __pycache__ │ │ ├── __init__.cpython-37.pyc │ │ ├── urls.cpython-37.pyc │ │ └── views.cpython-37.pyc │ ├── templates │ │ └── main │ │ ├── includes │ │ └── index.html │ ├── tests.py │ ├── urls.py │ └── views.py ├── manage.py ├── media ├── project │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-37.pyc │ │ ├── settings.cpython-37.pyc │ │ ├── urls.cpython-37.pyc … -
How to redirect to user profile page after log in?
I'm looking for a way to redirect to the user profile page after log in. The problem I'm facing is that I can figure out how to pass the user_id into the url to get the redirection to complete. I understand that this is a common issue and I've tried following many suggested solutions I found from other people's issues, however none have allowed me to find a solution. <div class='registration'> <form method="post" action="{% url 'auth_login' %}">{% csrf_token %} <p> &nbsp;{% trans form.username.label_tag %} &nbsp;{{ form.username }}</p> <p> &nbsp; {% trans form.password.label_tag %} &nbsp; {{ form.password }}</p> <p>{% blocktrans %}<a href="{{ auth_pwd_reset_url }}">Forgot</a> your password? </br> <a href="{{ register_url }}">Need an account</a>?{% endblocktrans %}</p> <input class='login-button' type="submit" value="{% trans 'login' %}" /> <input class= 'login-button'type="hidden" name="next" value="{{ next }}" /> </form> </div> LOGIN_REDIRECT_URL = '/' path('profile/<int:user_id>', core_views.user_profile, name='profile'), Things I've tried (LOGIN_REDIRECT_URL = '/profile/')- this gave me a 404 error. -(LOGIN_REDIRECT_URL = '/profile/')- this gave me a NoReverseMatch error. input class= 'login-button'type="hidden" name="next" value="{% url profile request.user_id %}" I've tried making a login in view but that didn't work either. I've been stuck for a while on this and any help would be greatly appreciated! -
Using ternary operators in Q objects and avoid query with None values
While chaining Q objects in django, how can I avoid using a Q object if a particular value is None? I wrote the following: print("Doing an AND search") SearchResult = customer.objects.filter( Q(cstid=HospitalID if HospitalID else None) & Q(insurance_number__lower__contains=insurance_number.lower() if insurance_number else None) & Q(name__lower__contains=name.lower() if name else None) & Q(ageyrs=ageyrs if ageyrs.isdigit() else None) & Q(agemnths=agemnths if agemnths.isdigit() else None) & Q(mobile__contains=mobile if mobile else None) & Q(alternate__contains=alternate if alternate else None) & Q(email__lower__contains=email.lower() if email else None) & Q(address__lower__contains=address.lower() if address else None) & Q(city__lower__contains=city.lower() if city else None) ,linkedclinic=clinicobj) SearchResult = customer.objects.filter(my_q, linkedclinic=clinicobj) I get the error: POST data <QueryDict: {'csrfmiddlewaretoken': ['YN6riYcjKaYUi6wtwPCY6AzqPt8JwL5VZiZKo0y8r4zBlBBv4ncpWLvubclroSVE'], 'HospitalID': [''], 'insurance_number': [''], 'name': [''], 'ageyrs': [''], 'agemnths': [''], 'email': ['rie'], 'mobile': [''], 'alternate': [''], 'address': [''], 'city': [''], 'include_all_terms': ['on']}> Doing an AND search 2019-08-11 01:04:33,826 django.request ERROR Internal Server Error: /clinic/checkin Traceback (most recent call last): File "/home/joel/myappointments/venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/joel/myappointments/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/joel/myappointments/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/joel/myappointments/venv/lib/python3.6/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "/home/joel/myappointments/clinic/views.py", line 2840, in checkin_patient_specific ORSearchResult = ORSearch_Patients(HospitalID, clinicobj, name, ageyrs, agemnths, mobile, alternate, email, address, … -
Registration problem in DJANGO REST FRAMEWORK
I have a User model and ı want to create user register API. I created API but it doesn't work. I think I did something wrong but ı can't fix it. it looks like on swagger UI like this: It doesn't show the body item in swagger UI How can ı fix this register problem? view.py: class RegistrationView(APIView): authentication_classes = (CsrfExemptSessionAuthentication,) # permission_classes = (XHROnly,) def post(self, request, *args, **kwargs): serializer = RegistrationSerializer(data=request.data) if serializer.is_valid(raise_exception=False): user = serializer.save() user = authenticate(email=user.email, password=serializer.validated_data['password1']) if user is not None: token, created = Token.objects.get_or_create(user=user) if user.is_active: login(request, user) return Response({'status': 'success', 'token': token.key, 'user': UserSerializer(user, context={'request': self.request}).data}, status=201) else: return Response({'status': 'success', 'token': token.key, 'user': UserSerializer(user, context={'request': self.request}).data}, status=201) else: return Response({'status': 'error', 'errors': serializer.errors}, status=203) else: return Response({'status': 'error', 'errors': serializer.errors}, status=203) serializers.py: class RegistrationSerializer(Serializer): full_name = CharField( max_length=200, style={'input_type': 'text', 'placeholder': 'İsim'} ) email = EmailField( max_length=100, style={'placeholder': 'Email'}) password1 = CharField( max_length=100, style={'input_type': 'password', 'placeholder': 'Şifre'} ) password2 = CharField( max_length=100, style={'input_type': 'password', 'placeholder': 'Şifre Tekrar'} ) def validate(self, data): if data['password1'] == data['password2']: return data else: raise ValidationError('Girdiğiniz şifreler uyuşmamakta.') def validate_full_name(self, value): return value def validate_email(self, value): try: user = User.objects.get(email=value) raise ValidationError("Bu email kullanılmaktadır.") except User.DoesNotExist: return … -
Django response setting a json as a cookie
I would like to set the value of a client side cookie from django as a javascript dictionary object. I know you can set a cookie value of a string like this in django: response = HttpResponseRedirect( reverse('app:home') ) response.set_cookie( 'cookiekey', 'value' ) return response I can then read the cookie on the client side like this: Cookies.get( 'cookiekey' ) using the Cookies library ( https://github.com/js-cookie/js-cookie ) What I am unable to do is set the cookie to be a dictionary/json object: I have tried this: response.set_cookie( 'cookiekey', {'value' : 'value'} ) and import json response.set_cookie( 'cookiekey', json.dumps( {'value' : 'value'} ) ) and then tried to read the cookie back on the client side using: Cookies.getJSON( 'cookiekey' ) but this doesn't seem to give me back a javascript dictionary object (neither does Cookies.get) but instead a string: var message = Cookies.getJSON( 'cookiekey' ); alert( typeof message ); -
Updating Django Model After Serialization from DRF
I currently have an API endpoint that receives data from the client and kicks of a scrapy crawler job. The problem is I need to create the Job model instance, kick off the scrapy job, then update the model with the task_id returned by the scrapy job. The model is successfully updated, but the serialized data returned by DRF does not have the updated data. I need to create the model instance prior to kicking off the job so that the scrapy job has the primary key of the job to update its status and add data as it finishes the job. I know why JSON response does not have my new data: I am updating the model in the view after DRF has done its work. I cannot edit the serialized data once .save() has been called on the serializer instance. views.py class StartJobView(views.APIView): def post(self, request): # map incoming 'id' field to 'client_id' request.data['client_id'] = request.data['id'] serializer = JobSerializer(data=request.data) if serializer.is_valid(): # create job entry serializer.save() id = serializer.data.get('id') # get pk to pass to spider settings = { 'id': id, } task_id = scrapyd.schedule('default', 'tester', settings=settings) Job.objects.filter(id=id).update(task_id=task_id) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) JSON response: { "id": … -
Serializce Multiple models in django
I need to serialize multiple models in order to have one single JSON as an answer. The serializers.py i made it's like this from rest_framework import serializers from .models import SnpsFunctionalelement,Snps,Functionalelement,Celllines class SnpsSerializer(serializers.ModelSerializer): class Meta: model = Snps fields = ['rsid'] class FunctionalElementSerializer(serializers.ModelSerializer): class Meta: model = Functionalelement fields = ['name'] class CelllinesSerializer(serializers.ModelSerializer): class Meta: model = Celllines fields = ['name'] class SnpsFunctionalelementSerializer(serializers.ModelSerializer): snps = SnpsSerializer(many = True) functional = FunctionalElementSerializer(many = True) cellline = CelllinesSerializer(many = True) class Meta: model = SnpsFunctionalelement fields = ['snps__rsid', 'functional__name', 'cellline__name', 'countexperiments', 'filetype'] def to_internal_value(self, data): snps_info = {kv: data[kv] for kv in data if kv in list(SnpsSerializer.Meta.fields)} functional_info = {kv: data[kv] for kv in data if kv in list(FunctionalElementSerializer.Meta.fields)} cellline_info = {kv: data[kv] for kv in data if kv in list(FunctionalElementSerializer.Meta.fields)} return super(SnpsFunctionalelementSerializer, self).to_internal_value({ 'snps__rsid': snps_info, 'functional__name': functional_info, 'cellline__name': cellline_info }) where to_internal_value is made for having a plain JSON made like this { "rsid":.... "name":.... ..... "filetype":... } { "rsid": ..... } etc. etc. but it gives me an error that says The field 'cellline' was declared on serializer SnpsFunctionalelementSerializer, but has not been included in the 'fields' option. So if someone could tell me if there is another way to … -
How to write sql COALESCE in Django
I'm new to Django. How to write COALESCE sql queryset in to django orm. query = 'SELECT COALESCE(max(CAST(order_no as UNSIGNED)), 0) as o,id from nanossc_Sales_master' models.py class Sales_master(models.Model): slno = models.IntegerField(blank=True, null=True) order_no = models.CharField(max_length=50, blank=True, null=True) type = models.CharField(max_length=50, blank=True, null=True) customer_id = models.CharField(max_length=50, blank=True, null=True) customer_name = models.CharField(max_length=50, blank=True, null=True) brand_name = models.CharField(max_length=50, blank=True, null=True) name = models.CharField(max_length=50, blank=True, null=True)