Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
non_field_errors : ["Expected a list of items but got type "dict"."]
I create realtime chat application using websocket frontend(angular) backend(Django).. I want to store messages in to db(mySql).. when I trying to store message from angular to django.. it give me error: non_field_errors: ["Expected a list of items but got type "dict"."] so what is wrong? model.py class msg(models.Model): name = models.ForeignKey(User, on_delete=models.CASCADE) receiver = models.CharField(max_length=20) text = models.CharField(max_length=1200) myDate = models.DateTimeField() serializer.py class MesSerializer(serializers.ModelSerializer): name = serializers.SlugRelatedField(many=False, slug_field='name', queryset=User.objects.all()) class Meta: model = msg fields = '__all__' view.py class msg_list(APIView): def get(self, request, format=None): mes = msg.objects.all() serializer = MesSerializer(mes, many=True) # convert into JSON return Response(serializer.data) def post(self, request, formate = None): serializer = MesSerializer(data=request.data, many = True) #type list if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=400) -
Django minimal queryset of last objects where there is n records meeting condition
I have a model Invoice: class Invoice(Model): datetime = DateTimeField(..) paid = BooleanField(..) I want to get queryset of n latest Invoices where paid = True but I want to include paid = False Invoices if there are some between n latest paid Invoices. So I want minimal queryset of latest Invoices where there is exactly n of them paid. Example: We have 8 invoices ordered by ("-created","-id"): datetime = 15.04.2018 14:00 paid = True ______________ datetime = 15.04.2018 13:00 paid = True ______________ datetime = 14.04.2018 14:00 paid = True ______________ datetime = 14.04.2018 14:00 paid = True ______________ datetime = 13.04.2018 14:00 paid = True ______________ datetime = 13.04.2018 14:00 paid = False ______________ datetime = 13.04.2018 14:00 paid = True ______________ datetime = 13.04.2018 14:00 paid = False ______________ If I want a queryset of 6 latest paid Invoices I will get all of them except the last one. The queryset will include 6th Invoice even if it's not paid yet. latest_n_paid = Invoice.objects.get(paid=True)[:n] first_paid_from_latest_n_paid = latest_n_paid.last() queryset = Invoice objects.filter(datetime__gte=first_paid_from_latest_n_paid.datetime) This would not work because it would return all Invoices since the last one has the same datetime as last paid Invoice. Do you know what β¦ -
Remove duplicate in datalist Python 2.7/Django
example, I have a list called attendances that contain multiple data like: [ <Attendance>: 11804 : 2018-07-18 12:22:55, <Attendance>: 11804 : 2018-07-18 12:23:04, <Attendance>: 2 : 2018-07-25 16:17:18, <Attendance>: 2 : 2018-07-25 16:17:20, <Attendance>: 2 : 2018-07-25 16:17:23, <Attendance>: 2 : 2018-07-25 16:27:52] when I need to print it. I do simply: for data in attendances: print 'User ID : {}'.format(data.user_id) print 'Timestamp : {}'.format(data.timestamp) result will be: User ID : 11804 Timestamp : 2018-07-18 12:22:55 User ID : 11804 Timestamp : 2018-07-18 12:23:04 User ID : 2 Timestamp : 2018-07-25 16:17:18 User ID : 2 Timestamp : 2018-07-25 16:17:20 User ID : 2 Timestamp : 2018-07-25 16:17:23 User ID : 2 Timestamp : 2018-07-25 16:27:52 but that not what I need, since its print all the data. I need to only show only one and first data every User ID. like this : User ID : 11804 Timestamp : 2018-07-18 12:22:55 User ID : 2 Timestamp : 2018-07-25 16:17:18 any have idea what should I do?... -
Django - Data can't update in wmi (ajax)
I'm using Django to write a project that can show some information about computer, but when I used ajax to update the information every 10 sec, time changed, CPU_utilization changed, but Remaining Capacity and Charge Rate didn't change. Everything changed except the info of battery using wmi. I think the point is wmi or pythoncom didn't update, but I don't know how to fix it. current function and update function in views.py def current(request): now=time() percent=battery() plugged=recharge() CPU_utilization=cpu_utilization() CPU_numbers=cpu_numbers() #get info of battery using wmi pythoncom.CoInitialize() c = wmi.WMI() t = wmi.WMI(moniker = "//./root/wmi") batts = t.ExecQuery('Select * from BatteryFullChargedCapacity') for i, b in enumerate(batts): FCC=str(b.FullChargedCapacity)+'mWh' batts = t.ExecQuery('Select * from BatteryStatus where Voltage > 0') for i, b in enumerate(batts): RC=b.RemainingCapacity vol=str(b.Voltage)+'mV' DR=str(b.DischargeRate)+'mW' CR=str(b.ChargeRate)+'mW' pythoncom.CoUninitialize() #--------------------------------- context = {'now': now, 'percent': percent, 'plugged': plugged, 'CPU_utilization':CPU_utilization, 'CPU_numbers':CPU_numbers, 'FCC': FCC, 'RC': RC, 'vol': vol, 'DR': DR, 'CR':CR} return render(request, 't1/index.html', context) def update(request): #same as current(request) return JsonResponse({'latest_results_list':context}) templates {% if now %} <div class="wrap" id ='myTable'> <ul> <li>time: <a>{{ now }}</a></li> <li>battery: <a>{{ percent }}</a></li> <li>plugged: <a>{{ plugged }}</a></li> <li>CPU utilization: <a>{{ CPU_utilization }}</a></li> <li>Logical processors / Cores: <a>{{ CPU_numbers }}</a></li> <li>Fully Charged Capacity: <a>{{ FCC }}</a></li> <li>Remaining Capacity: <a>{{ β¦ -
TypeError: expected str, bytes or os.PathLike object, not ImageFieldFile
I am trying to upload a file to an another server. I am trying to do it like that: package = Package.objects.get(id=package_id) with open(package.logo_image.image, 'rb') as image_handle: image_data = bytes(image_handle.read()) image = { 'type': 'IMAGE', 'data': image_data, 'xsi_type': 'Image' } logo_image = media_service.upload(image)[0] Field in a model: image = models.ImageField(upload_to=generate_file_path, null=True, blank=True) AFter trying to run this code I get: with package.marketing_image.image.read() as image_handle: TypeError: expected str, bytes or os.PathLike object, not ImageFieldFile Converting to str() does not help. Is is possoble to open this file i binary mode? Thank you! -
Purpose of django.db.models.fields.Field.name argument
Recently i discovered that there is not-documented django.db.models.fields.Field.name option: @total_ordering class Field(RegisterLookupMixin): # here we have it ... βββββββββ def __init__(self, verbose_name=None, name=None, primary_key=False, max_length=None, unique=False, blank=False, null=False, db_index=False, rel=None, default=NOT_PROVIDED, editable=True, serialize=True, unique_for_date=None, unique_for_month=None, unique_for_year=None, choices=None, help_text='', db_column=None, db_tablespace=None, auto_created=False, validators=(), error_messages=None): ... There is mention of it in doc-way: # A guide to Field parameters: # # * name: The name of the field specified in the model. # * attname: The attribute to use on the model object. This is the same as # "name", except in the case of ForeignKeys, where "_id" is # appended. # * db_column: The db_column specified in the model (or None). # * column: The database column for this field. This is the same as # "attname", except if db_column is specified. # # Code that introspects values, or does other dynamic things, should use # attname. For example, this gets the primary key value of object "obj": # # getattr(obj, opts.pk.attname) Description above is related with #683 ([patch] Saving with custom db_column fails) ticket. So if we look through whole django.db.models.fields.Field class, this seems as name option is setting attribute name, which make real name of variable invalid: Suppose we β¦ -
Request data in Django
I have a view inheriting Django Rest Framework mixins - class ChartQueryView(mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin, mixins.CreateModelMixin, generics.GenericAPIView): queryset = ChartQueryMap.objects.all() serializer_class = ChartQuerySerializer def get(self, request, *args, **kwargs): print("request inside get", dir(request)) The dir of request is printed - ['DATA', 'FILES', 'POST', 'QUERY_PARAMS', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattr__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_auth', '_authenticate', '_authenticator', '_content_type', '_data', '_default_negotiator', '_files', '_full_data', '_load_data_and_files', '_load_stream', '_not_authenticated', '_parse', '_request', '_stream', '_supports_form_parsing', '_user', 'accepted_media_type', 'accepted_renderer', 'auth', 'authenticators', 'content_type', 'data', 'force_plaintext_errors', 'negotiator', 'parser_context', 'parsers', 'query_params', 'stream', 'successful_authenticator', 'user', 'version', 'versioning_scheme'] I cant find the META or COOKIES here. Am I missing something or viewing at wrong place? -
multiple annotate and aggregate with order-by and distinct in django
I am still confused with use of annotate, aggregate, what i have done is: top_spenders_by_cost = StoreInvoice.objects.filter(store_id=store_id)\ .annotate(customer_invoice_count=Count('customer_id'))\ .annotate(customer_total_purchase=Sum('total'))\ .order_by('-customer_total_purchase')\ .values(name=F('customer_id__first_name'))\ .distinct()[:int(top_count)] The StoreInvoice Model Looks like: id = --AutoCreatedByDjango store = ForeignKey(store) customer = ForeingKey(customer) total = IntegerField() ...some other fields What I am doing is: 1. Filter all StoreInvoices by store_id, 2. group invoices by customer_id as customer_invoice_count 3. find sum of total of all StoreInvoice for each customer_id group as customer_total_purchase 4. then order result by maximum total at top of list In short I want to retrieve top 10 customer_name list ordered by maximum sum of total for each customer_id The problem is it returns duplicate records i.e. same customer, so logically there is something wrong with the second annotation, i tried using aggregate to find sum, but values don't work on that, as it returns me single value i.e. sum value. Also I want the sum of all total for each customer_id i.e. pass the sum of total i.e. customer_total_purchase in values along. The return shall look like: { "customer_name": abcd, "customer_total_purchase": 52.6 } -
receiving incomplete data when using python requests
I'm crawling a website and gathering it's data. I have some crawler machine, where they send data to a central server. Part of code in crawlers which send data to server is as follows : requests.post(url, json=data, timeout=timeout, cookies=cookies, headers=headers) At the central server side which uses django, I have the following code: def save_users_data(request): body = json.loads(request.body) // do something on data received sometimes server receives incomplete data from crawlers and so json package cannot load data and raises error. For example server received following data in request.body : b'{"social_network": "some network", "text": "\\u0646\\u06cc\\u0633 \\u0628\\u0627\\u06cc\\u062f \\u0622\\u062a\\u06cc\\u0634 \\u062f\\u0631\\u0633\\u062a \\u06a9\\u0631\\u062f\\u0628\\u0631\\u06af\\u0634\\u062a\\u' and raises following error : json.decoder.JSONDecodeError: Invalid \uXXXX escape Where is the problem? -
Best way to have order_by and distinct different columns in Django?
I'm trying to do the following with a POSTGRESQL DB: team_updates = TeamUpdate.objects.filter(team__in = TeamStarred.objects.filter(user=request.user).values('team')) team_updates = team_updates.order_by('-date','team__name').distinct('team__name') This would technically solve the problem, but it causes the ordering to now be by team_name rather than date. team_updates = TeamUpdate.objects.filter(team__in = TeamStarred.objects.filter(user=request.user).values('team')) team_updates = team_updates.order_by('team__name', '-date').distinct('team__name') -
Django admin page structure for multiple organizations
I'm currently building an Django application which could be used by several different organizations, each would have their own group of users. The goal is that staff from one organization can only see/edit model instances added by its own staff in the admin page. Each organization will also have an admin who can add revoke the rights of a staff member in their organization. So how should I go about with this and how do I custom my admin page? Do I need to create custom model for User./Organization or just django group would do? -
DRF, add custom field to ModelSerializer
I have some models in my project and I need a especial response of the API, i'm using Django Rest framework. class Goal(models.Model): name = models.CharField() # more fields class Task(models.Model): name = models.CharField() goal = models.ForeignKey(Goal) class UserTask(models.Model): goal = models.ForeignKey(Goal) user = models.ForeignKey(User) # other fields I have this response: { "name": "One goal", "task": [ { "name": "first task" }, { "name": "second tas" } ] } But I need this: { "name": "One goal", "task": [ { "name": "first task", "is_in_usertask": true }, { "name": "second tas", "is_in_usertask": false } ] } I saw this in DRF docs but I don't know how to filter UserTask by the current user (or other that is given in URL paramenter) and each Goal. -
Django Window Expression using cumedist, filter, order_by
In Django 2.0 I am trying order a queryset descending by date all the objects. Then filter by a parameter, but then I would also like to annotate the filtered query set using a Window (or maybe something else) with the gap between the queryset before the filter. I know that sounds weird I just don't know how to explain it better. I will try to visualize below. I have a show class: class Show(models.Model): date = models.DateField() name = models.CharField() This is the code I have so far: def name_filter(self, in_name) Show.objects.all().order_by('date').filter(name=in_name) .annotate(show_gap=Window(expression=CumeDist())) So basically what I am trying to do is find the number of shows (the gap) between the filtered results. So for example if the data was such as below. date name 01/01/14 alpha 10/10/13 bravo 05/05/12 charlie 06/06/11 alpha 04/04/10 delta I would call: name_filter('alpha') And I would get back a queryset of the alpha objects with an annotation of show_gap that would let me know that there was a 3 show gap between them. So the final result would be like below with the gap between the two alphas. The second result is a show gap of 1 because that is relative to the β¦ -
How do I improve my 'for' loop performance in terms of speed?
I have a for loop which it is taking almost 20 seconds for iterating 6907 rows. That loop does the job of making a list of unique region names in the given queryset. I have placed timestamps at various places in the code to record the timings. The 'for' loop which is taking more time is between variables 't3' and 't4'. timestamps t = 12:27:22:169533 t2 = 12:27:22:173535 t3 = 12:27:22:793567 6907 t4 = 12:27:42:907362 t5 = 12:27:43:242596 t6 = 12:27:43:242596 6907 is the length of my queryset sales_data views.py class MSZoneProduct(generic.TemplateView): template_name = 'sales/MSZoneProduct.html' form_class = MSZoneProductForm def get(self, request, *args, **kwargs): if request.user.is_authenticated: form = self.form_class(request.GET) context = {'form': form} if form.is_valid(): zone_code_ = form.cleaned_data['zone_name'] product_code_ = form.cleaned_data['product_name'] t = datetime.now().strftime('%H:%M:%S:%f') print("t = " + t) product = Product.objects.get(product_code=product_code_) t2 = datetime.now().strftime('%H:%M:%S:%f') print("t2 = " + t2) sales_data = Sales.objects.filter(zone_code=zone_code_, product_code=product).select_related() t3 = datetime.now().strftime('%H:%M:%S:%f') print("t3 = " + t3) print(len(sales_data)) regions = [] message = "" regions_dict = {} for x in sales_data: if x.region_name not in regions: regions.append(x.region_name) else: continue t4 = datetime.now().strftime('%H:%M:%S:%f') print("t4 = " + t4) for x in regions: sum_ = 0 for y in sales_data: if y.region_name == x: sum_ = sum_ + β¦ -
Django: Forms Queryset
I wonder if that is the right approach. I first call queryset=Reward.objects.all() just to change it right after and filter it. However, I couldn't come up with a better solution. Do you have any thoughts on that? class ClaimRewardForm(forms.ModelForm): note = forms.CharField(widget=forms.Textarea) title = forms.ModelChoiceField(queryset=Reward.objects.all()) # note = forms.DropDown() class Meta: model = Reward fields = ['title'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['title'].queryset = Reward.objects.filter(event=self.initial['event']) -
Django-fsm : Dynamic Targets fail due to extra method parameters
https://github.com/kmmbvnr/django-fsm#target Original example in docs: @transition( field=state, source='for_moderators', target=GET_STATE( lambda self, allowed: 'published' if allowed else 'rejected', states=['published', 'rejected'])) def moderate(self, allowed): self.allowed=allowed I'm using the above approach to resolve dynamic target states. My function looks like this: @fsm_log_by @transition( field=state, source=[constants.BookingState.on_hold], target=GET_STATE( lambda self: constants.BookingState.camop_assigned if self.camera_operator else constants.BookingState.active, states=[constants.BookingState.active, constants.BookingState.camop_assigned]), permission=can_make_active, ) def make_active(self, by=None): async('some async task', self.pk) async('some other async task', self.pk) I have an additional by=None which is used for logging purposes. However, when I run this function, it says: <lambda>() got an unexpected keyword argument 'by' I don't understand why lambda is considering the parameter which I have not even declared in the lambda. I can run it if I remove by=None from the make_active function but I cannot do that as it is an important parameter. Please help. -
How to group by date in django mongoengine
my model: Class Post(Documet): date = fields.DateTimeField() count = fields.IntField(default=1) values are: 2018-07-25T23:00:99 1 2018-07-25T12:00:07 1 2018-07-24T03:00:00 1 2018-07-24T00:09:34 1 2018-07-23T07:00:00 1 expected result: 2018-07-25 2 2018-07-24 2 2018-07-23 1 -
'User' object has no attribute 'image'
Got AttributeError when attempting to get a value for field image on serializer UserSerializer. The serializer field might be named incorrectly and not match any attribute or key on the User instance. Original exception text was: 'User' object has no attribute 'image'. The problem is that I cant upload image to the userprofile model.Without the image field everything works fine.How can I make this right. here is the models.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save class UserProfile(models.Model): objects = models.Manager() user = models.OneToOneField(User, on_delete=models.CASCADE) description = models.CharField(max_length=100, default='') city = models.CharField(max_length=100, default='') website = models.URLField(default='') phone = models.IntegerField(default=0) images = models.ImageField(upload_to='profile_image', blank=True) def __str__(self): return self.user.username def create_profile(sender, **kwargs): if kwargs['created']: user_profile = UserProfile.objects.create(user=kwargs['instance']) post_save.connect(create_profile, sender=User) this is the serializer.py from rest_framework import serializers from rest_framework.validators import UniqueValidator from django.contrib.auth.models import User from accounts.models import UserProfile class UserSerializer(serializers.ModelSerializer): description = serializers.CharField( required=False) city = serializers.CharField(required=False) mobile = serializers.IntegerField(required=False) website = serializers.URLField(required=False) email = serializers.EmailField( required=True, validators=[UniqueValidator(queryset=User.objects.all())] ) username = serializers.CharField( validators=[UniqueValidator(queryset=User.objects.all())] ) password = serializers.CharField(min_length=8) first_name = serializers.CharField(validators=None,max_length=100, required=True) last_name = serializers.CharField(validators=None, max_length=100, required=True) image = serializers.ImageField() class Meta: model = User fields = [ 'username', 'email', 'first_name', 'last_name', 'description', 'city', 'website', 'mobile', 'image', β¦ -
In order to allow non-dict objects to be serialized set the safe parameter to False
I create realtime chat application using websocket frontend(angular) backend(Django).. i want to store messages in to db(mySql)..when i trying to store message array from angular to django..it give me error like 500 internal server Eroor and In order to allow non-dict objects to be serialized set the safe parameter to False. i sending message data in list array.. so what is wrong? model.py class msg(models.Model): name = models.ForeignKey(User, on_delete=models.CASCADE) receiver = models.CharField(max_length=20) text = models.CharField(max_length=1200) myDate = models.DateTimeField() serializer.py class MesSerializer(serializers.ModelSerializer): name = serializers.SlugRelatedField(many=False, slug_field='name', queryset=User.objects.all()) receiver = serializers.SlugRelatedField(many=False, slug_field='name', queryset=User.objects.all()) class Meta: model = msg fields = '__all__' view.py class msg_list(APIView): def get(self, request, format=None): mes = msg.objects.all() serializer = MesSerializer(mes, many=True) # convert into JSON return Response(serializer.data) def post(self, request, formate = None): data = JSONParser().parse(request) #type list serializer = MesSerializer(data= data, many = True) #type list if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=400) -
Django segmentation fault while running in docker
We are getting segmentation fault while running the application in docker /path/condapy/envs/env_name/bin/python -vvvvvv manage.py runserver # code object from '/path/condapy/envs/env_name/lib/python3.6/site-packages/django/core/__pycache__/wsgi.cpython-36.pyc' import 'django.core.wsgi' # <_frozen_importlib_external.SourceFileLoader object at 0x7f1919dd5a90> import 'django.core.servers.basehttp' # <_frozen_importlib_external.SourceFileLoader object at 0x7f1919dca240> import 'django.core.management.commands.runserver' # <_frozen_importlib_external.SourceFileLoader object at 0x7f1919dbf630> import 'django.contrib.staticfiles.management.commands.runserver' # <_frozen_importlib_external.SourceFileLoader object at 0x7f1919db34a8> PyThreadState_Clear: warning: thread still has a frame Running in local mode Performing system checks... Segmentation fault -
Override change_form.html in django
I have built a Content Management System where I am able to upload photos, single photo at a time. Now I need to allow multiple photo upload option simultaneously. For doing that, I'm following this blog post https://blog.rousek.name/2017/08/11/uploading-multiple-files-in-django-admin/. It tells that there should be an admin directory inside templates inside my_app inside my_project. Many other resources on googling also suggested the same thing. Inside that admin directory is where I'll find the models and there change_form.html which I need to override. But I'm not able to find the admin directory itself. This is my project directories tree. . βββ cms β βββ admin.py β βββ forms.py β βββ __init__.py β βββ migrations β β βββ 0001_initial.py β β βββ __init__.py β βββ models.py β βββ Roboto-Bold.ttf β βββ tests.py β βββ urls.py β βββ views.py βββ manage.py βββ media β βββ images βββ Procfile βββ README.md βββ requirements.txt βββ Roboto-Bold.ttf βββ static β βββ css β β βββ bootstrap.css β β βββ bootstrap-fluid-adj.css β β βββ bootstrap.min.css β β βββ bootstrap-responsive.css β β βββ bootstrap-responsive.min.css β βββ img β β βββ glyphicons-halflings.png β β βββ glyphicons-halflings-white.png β βββ js β βββ bootstrap.js β βββ bootstrap.min.js β βββ jquery β βββ β¦ -
How to add extra fields to Django Queryset
I'd like to add some extra fields to my queryset. models.py class Company(models.Model): ENTITY_CHOICES = ( ('CO', 'Corporation'),('PR','Proprietor'),('PA','Partnership'),('NO','Nonprofit')) legal_name = models.CharField(max_length=120, blank=True) entity = models.CharField(max_length=1, null=True, choices=ENTITY_CHOICES, default='CO') client = models.ForeignKey(Clients, models.SET_NULL, blank=True, null=True) views.py qs = Company.objects.filter(entity=PA) for q in qs: q.due_date = '06/15' for q in qs: print('due_date',q.due_date) It was successful in many times. But the result is not stable and I happen to see errors as follows, Exception Type: AttributeError Exception Value: 'Companies' object has no attribute 'due_date' Is there any better way to add extra attribute to querysets? -
Best pattern for AWS Cognito / React frontend / Django Rest backend
Struggling to get this fully working - here is my app workflow: React frontend - user authenticates w/ Cognito directly (using AWS Amplify) - I've got this working fine. The frontend needs to handle this, as it makes separate direct calls to other AWS services. DRF backend - React then makes API calls to DRF endpoints using Amplify.API, which includes the x-amz-security-token in the request header (this appears to be the Session Token returned by Amplify's call to the cognito-idp service). So now the backend has the Session Token (but not the Access Token or Refresh Token) The backend then simply needs to verify that the frontend user (whose authenticated identity I assume is represented by the Session Token) is a valid and currently authenticated user according to Cognito. So the backend needs to make a separate call to Cognito to verify this. This is where I'm failing - I've looked at django-warrant, but I can't discern from the documentation whether this is appropriate for my use case (or even how to really use it - the default setup suggested results in various boto3 errors to do w/ lack of credentials, etc.). I've also looked at warrant and directly at β¦ -
Get nested serialized data as one
Actual Return { "store_product_mapping":{ "master_product":{ "name": "abc", "description": "xyz" } } "selling_price": 445 } Serializers looks like: class GrandParentSerializer(serializers.ModelSerializer): class Meta: model = Z fields = ('name', 'description') class ParnetSerializer(serializers.ModelSerializer): master_product = GrandParentSerializer(many=False, read_only=False) class Meta: model = Y fields = ('master_product',) class ChildSerializer(serializers.ModelSerializer): store_product_mapping = ParnetSerializer(many=False, read_only=False) class Meta: model = X fields = ('store_product_mapping', 'selling_price') Am using nested rest_framework.serializer.ModelSerializer to serialize the data from multiple levels but in response i need it to be like. Do I need to make a new dictionary and in a loop update the dictionary? Or is there a shortcut to do same? { "name": xyz "description": abcd "price": 10 } -
Django Best Practices -- Migrating Data
I have a table with data that must be filled by users. Once this data is filled, the status changes to 'completed' (status is a field inside data). My question is, is it good practice to create a table for data to be completed and another one with completed data? Or should I only make one table with both types of data, distinguished by the status?