Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why my serializer gets only one image instead of multiple (Rest Framework)
I am trying to upload multiple images with this serializer but it only accepts one image . View class ArticleView(CreateAPIView): queryset = Article.objects.all() serializer_class = ArticleViewSerializer permission_classes = (AllowAny,) parser_classes = (MultiPartParser, FormParser,) def get(self, request, format=None): queryset = Article.objects.all() serializer = ArticleViewSerializer() return Response(serializer.data) def post(self, request, *args, **kwargs): serializer = ArticleViewSerializer(data=request.data) if serializer.is_valid(): article = serializer.save() serializer = ArticleViewSerializer(article,many=True) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) class ArticleImagesView(CreateAPIView): queryset = ArticleImages.objects.all() serializer_class = ArticleImagesViewSerializer permission_classes = (AllowAny,) parser_classes = (MultiPartParser, FormParser,) def get(self, request, format=None): queryset = ArticleImages.objects.all() serializer = ArticleImagesViewSerializer() return Response(serializer.data) def post(self, request, *args, **kwargs): serializer = ArticleImagesViewSerializer(data=request.data) if serializer.is_valid(): articleimages = serializer.save() serializer = ArticleImagesViewSerializer(articleimages,many=True) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Serializer class ArticleImagesViewSerializer(serializers.ModelSerializer): class Meta: model = ArticleImages fields = ('id','image') def create(self, validated_data): return ArticleImages.objects.create(**validated_data) class ArticleViewSerializer(serializers.ModelSerializer): imageset = ArticleImagesViewSerializer(required=False,many=True) class Meta: model = Article fields = ('imageset','id','author') def create(self, validated_data): images_data = self.context.get('view').request.FILES article = Article.objects.create(**validated_data) for image_data in images_data.values(): ArticleImages.objects.create(article=article, image=image_data) return article When i send a postman request to my django serializer,it only accepts one imageset ,like this: "imageset": [{ "id": "ec7b9665-92cd-4a8c-ba16-d62b4c24dfca", "image": "http://127.0.0.1:8000/images/images/download2_dmpBXZQ.png"}], I have also coded my def create() function such that it enters into loop,but i know … -
Django Celery: create periodic task at runtime with schedule depending on user input
I have a simple Django (v3.1) app where I receive data from a form, process it with a view and then pass it on to Celery (v4.4.7, RabbitMQ as broker). Depending on the data submitted in the form, it can be a one-time task or a periodic task. The periodic task should have a start date, end date and an intervall (e.g.: execute every 2 days at 4pm, starting now until 4 weeks). My view (shortened and renamed for illustration purposes, of course): # views.py if request.method == 'POST': form = BackupForm(request.POST) if form.is_valid(): data = ... if not form.cleaned_data['periodic']: celery_task = single_task.delay(data) else: schedule = { 'first_backup': form.cleaned_data['first_backup'], 'last_backup': form.cleaned_data['last_backup'], 'intervall_every': form.cleaned_data['intervall_every'], 'intervall_unit': form.cleaned_data['intervall_unit'], 'intervall_time': form.cleaned_data['intervall_time'], } celery_task = periodic_task.delay(data, schedule) return HttpResponseRedirect(reverse('app:index')) The single task looks like this: # tasks.py @shared_task def single_task(data: dict) -> None: asyncio.run(bulk_screen(data=data)) This works well for a single task. However, I don't know how to adapt this to create dynamic periodic tasks. My schedule data varies, depending on the users' form input. I have to create the periodic task at runtime. According to the official documentation on periodic tasks, crontab schedules is what I need: from celery.schedules import crontab app.conf.beat_schedule = { # … -
anytomany field and a foreignkey to the same model class in a django model
How can I set a manytomany field and a foreignkey to the same model class in a django model. My data structure is similar to a linking list. class cls_object(models.Model): child = models.ManyToManyField('cls_object') parent = models.ForeignKey('cls_object', on_delete=models.CASCADE, blank=True, null=True) django always tells me to change one of the two: ERRORS: cls_object: (fields.E304) Reverse accessor for 'cls_object.child' clashes with reverse accessor for 'cls_object.parent '. HINT: Add or change a related_name argument to the definition for 'cls_object.child' or 'cls_object.parent'. cls_object: (fields.E304) Reverse accessor for 'cls_object.parent' clashes with reverse accessor for 'cls_object.child'. HINT: Add or change a related_name argument to the definition for 'cls_object.parent' or 'cls_object.child'. i would like to have the opportunity to find out its parents from the respective object and have to know which objects emanate from it. A loop would not be possible (syntax, of course, yes). should one possibly do this differently? The error is sure that he does not know how to resolve it clearly in the database, but something like that should work anyway, right? am I completely wrong? -
Query multiple tables with manytomany relationship and also check against a timestamp that is in the through table
Here's a simplified version of my model class: class BlogPost(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) content = models.TextField(blank=True, null=True) timestamp = models.DateTimeField(auto_now_add=True) class UserProfile(models.Model): user = models.OneToOneField(User, related_name = 'profile') first_name = models.CharField(max_length=120, blank=True, null=True) last_name = models.CharField(max_length=120, blank=True, null=True) following = models.ManyToManyField(User, related_name = 'followed_by', blank=True, through='FollowingRelation') class FollowingRelation(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) userprofile = models.ForeignKey(UserProfile, on_delete=models.CASCADE) timestamp = models.DateTimeField(auto_now_add=True) I'd like to query all rows from BlogPost that have been created by the session user, plus all other posts created by the users that the sessionUser is following, but has a timestamp greater than or equal to the timestamp when the session user started following. The raw sql query is something like this: select * from blog_blogpost A where A.user_id = sessionuserid or A.timestamp >= ( select timestamp from userprofile_followingrelation where user_id = A.user_id and userprofile_id = (select id from userprofile_userprofile where user_id = sessionuserid) ) I am unable to build this query in django. -
How to backup postgis database via terminal in linux?
I tried to back up a PostGIS database via terminal from the info from the site https://postgis.net/workshops/postgis-intro/backup.html like this pg_dump --file=test_pro.backup --format=c --port=5432 --username=postgres test_pro but I am encountering an error like this pg_dump: [archiver (db)] query failed: ERROR: could not access file "$libdir/postgis-2.5": No such file or directory pg_dump: [archiver (db)] query was: SELECT a.attnum, a.attname, a.atttypmod, a.attstattarget, a.attstorage, t.typstorage, a.attnotnull, a.atthasdef, a.attisdropped, a.attlen, a.attalign, a.attislocal, pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, array_to_string(a.attoptions, ', ') AS attoptions, CASE WHEN a.attcollation <> t.typcollation THEN a.attcollation ELSE 0 END AS attcollation, a.attidentity, pg_catalog.array_to_string(ARRAY(SELECT pg_catalog.quote_ident(option_name) || ' ' || pg_catalog.quote_literal(option_value) FROM pg_catalog.pg_options_to_table(attfdwoptions) ORDER BY option_name), E', ') AS attfdwoptions FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t ON a.atttypid = t.oid WHERE a.attrelid = '23466'::pg_catalog.oid AND a.attnum > 0::pg_catalog.int2 ORDER BY a.attnum this is my django database setting DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'test_pro', 'USER': 'postgres', 'PASSWORD': 'test_pro', 'HOST': 'localhost', 'PORT': '5432', } } what can I do to backup the PostGIS database via the terminal in linux -
django admin site has been occurred with s3, cloudfront
enter image description here enter image description here As you can see above, I'm using AWS S3 and Cloudfront through the django-storages library. But since I recently started using the cloudfront key, 403 errors have occurred on the admin site. -
Django error updating -> invalid literal for int() with base 10
i have the following problem when i tried to update a Ingredient... Internal Server Error: /menu/edit-plate/a6bf6537-878e-4321-8446-f3caad5a71dc Traceback (most recent call last): File "/home/l30n4rd0/.local/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 1774, in get_prep_value return int(value) ValueError: invalid literal for int() with base 10: 'a6bf6537-878e-4321-8446-f3caad5a71dc' ¿Can you help me? Here my code: Model: from django.db import models from django.urls import reverse import uuid from menu.models.ingredient import Ingredient class Plate(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text="ID único para este plato") title = models.CharField(max_length=200) ingredient = models.ManyToManyField(Ingredient, help_text="Seleccione un ingrediente para este plato") def __str__(self): """ String que representa al objeto Book """ return self.title def get_absolute_url(self): """ Devuelve el URL a una instancia particular de Menu """ return reverse('plate-details', args=[str(self.id)]) def get_edit_url(self): """ Devuelve el URL a una instancia particular de Menu """ return reverse('edit-plate', args=[str(self.id)]) View functions: class PlateCreate(generic.CreateView): model = Plate fields = ['title', 'ingredient'] success_url = 'plate-list' class PlateDetailView(generic.DetailView): model = Plate class PlateUpdate(generic.UpdateView): model = Ingredient fields = ['title', 'ingredient'] template_name_suffix = '_update_form' success_url = '/menu/plate-list' class PlateListView(generic.ListView): model = Plate Template: <form method="post"> {{ form.as_p }} {% csrf_token %} <input type="submit" value="Update"> </form> Urls.py from django.conf.urls import url from django.urls import path, include from . import views urlpatterns = [ url(r'^create-plate$', views.PlateCreate.as_view(), name='create-plate'), url(r'^plate-list/$', … -
How to fix Facebook has detected MyAppName isn't using a secure connection to transfer information
I am trying to implement facebook social Oauth login on my Django app but I am faced with the below error. I have tried changing my http protocol from http to https on Valid OAuth Redirect URIs. But I am still faced with the same problem. -
Deploy Django app on Microsoft Azure with Local Package
I would like to deploy an Django App on to Microsoft Azure through the App Service. In the requirements.txt I have a package that I wrote myself and need to install from local directory which is in the same directory as manage.py. I have tried to deploy the app through local git, and everytime it is running into the error it is not able to import the local package although it is able to install it with no problem in "antenv" (the virtual env Azure creates automatically) -
'decimal.Decimal' object is not iterable an error occurred django
im getting an error while trying to loop and get total of a decimal object in a django model, tried so many soloutions all failed. thr error is 'decimal.Decimal' object is not iterable and here is the model and object.. class Order(models.Model): # customer = models.ForeignKey(Customer, on_delete=models.CASCADE) total_price = models.DecimalField(max_digits=10, decimal_places=2, default=0) #success = models.BooleanField(default=False) timestamp = models.DateTimeField(auto_now=True) # product = models.ForeignKey(Product, on_delete=models.CASCADE) def __str__(self): return 'Order {0}'.format(self.id) @property def order_prices(self): order = 0 for o in self.total_price: order += o return order -
How can I get unread messages for each user?
I'm creating a django web application. I want to create a one way messaging system so users can receive messages from admin. Currently I did this using a model like below: from django.db import models from django.contrib.auth.models import User class AdminMessage(models.Model): title = models.CharField(max_length=120) receivers = models.ManyToManyField(User) message = models.TextField() is_read = models.BooleanField(default=False) the problem is I want each user to be able to see his unread messages in his profile. how can I do that? -
Can't update image in Django
I want to update image for ImageField but it won't update it's keep using default.jpg Here my models.py Here my form.py addproduct.html addproduct in views.py Thank you -
Memory Error while doing `request.POST.copy()'
I have a Django application that allows users to upload files. I do that using tastypie rest, it works perfectly with normal size files. but an error occurs when uploading a 500MB file. the error occurs at: multipart_data = request.POST.copy() The error is: Traceback (most recent call last): File "<env_path>\lib\site-packages\tastypie\resources.py", line 227, in wrapper response = callback(request, *args, **kwargs) File "<env_path>\lib\site-packages\tastypie\resources.py", line 467, in dispatch_list return self.dispatch('list', request, **kwargs) File "<env_path>\lib\site-packages\tastypie\resources.py", line 499, in dispatch response = method(request, **kwargs) File "<env_path>\lib\site-packages\tastypie\resources.py", line 1405, in post_list deserialized = self.deserialize(request, request.body, format=request.META.get('CONTENT_TYPE', 'application/json')) File "<project_path>\apps\data_manager\rest.py", line 70, in deserialize multipart_data = request.POST.copy() File "<env_path>\lib\site-packages\django\core\handlers\wsgi.py", line 110, in _get_post self._load_post_and_files() File "<env_path>\lib\site-packages\django\http\request.py", line 315, in _load_post_and_files self._post, self._files = self.parse_file_upload(self.META, data) File "<env_path>\lib\site-packages\django\http\request.py", line 275, in parse_file_upload return parser.parse() File "<env_path>\lib\site-packages\django\http\multipartparser.py", line 254, in parse chunk = handler.receive_data_chunk(chunk, counters[i]) File "<env_path>\lib\site-packages\django\core\files\uploadhandler.py", line 174, in receive_data_chunk self.file.write(raw_data) MemoryError -
Django get list of all models
I'm new in python and django. I have a file models.py in MyApp folder, It has about 20 model classes. I want to write a class that find all models in the MyApp and change the manager=True. from django.db import models class Model_One(models.Model): ... class Meta : managed = False class Model_Two(models.Model): ... class Meta : managed = False ... -
ufw forbids docker container to connect to postgres
On ubuntu 18.04 with ufw enabled I run docker container which is supposed to connect a django app to a locally installed Postgresql server. Everything runs perfect when ufw is disabled docker-compose -f docker-compose.prod.yml run --rm app sh -c 'python manage.py createsuperuser' But with enabled ufw I get the following error: conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError: could not connect to server: Operation timed out Is the server running on host "host.docker.internal" (172.17.0.1) and accepting TCP/IP connections on port 5432? I have following ufw rules $ sudo ufw status Status: active To Action From -- ------ ---- Nginx Full ALLOW Anywhere OpenSSH ALLOW Anywhere 20/tcp ALLOW Anywhere 21/tcp ALLOW Anywhere 990/tcp ALLOW Anywhere 40000:50000/tcp ALLOW Anywhere Nginx Full (v6) ALLOW Anywhere (v6) OpenSSH (v6) ALLOW Anywhere (v6) 20/tcp (v6) ALLOW Anywhere (v6) 21/tcp (v6) ALLOW Anywhere (v6) 990/tcp (v6) ALLOW Anywhere (v6) 40000:50000/tcp (v6) ALLOW Anywhere (v6) -
How to automatically move my settings.toml to a settings.yaml when using dynaconf
I am using Dynaconf to manage configurations of my Django project. Dynaconf sucessfully generated a settings.toml file with the current development environment. I want to switch to using .yaml format that I read dynaconf supports. Is there an automatic way to translate the settings.toml to an settings.yaml using dynaconf cli? -
Pass a list to geodjango multipolygon lookup
I have a list of points like following: points_list = ['SRID=4326;POINT (-86.81013299999999 33.524658)', 'SRID=4326;POINT (-86.81255400000001 33.524854)'] Now I want to use this list to filter on a MultipolygonField. I can't pass this whole list to the multipolygon lookup because I get an error, Tuple too long for lookup covers. Now what I have done is simply loop through the list and save the filtered multipolygon objects in a new list like: Say geom below is a multipolygon field multipolygon_list = [] for point in points_list: dam_obj = DAM.objects.filter(geom__contains=point).values_list('id', flat=True) multipolygon_list.append(dam_object) Now what I want is to remove the loop above and all this is a single query. Is there a way to remove it? Like can't I do something like below? DAM.objects.filter(geom__contains=points_list)... -
trade off of different ways to access postgresql data within django
I am unclear about something. I have a script where I do a lot of data wrangling from django models using pandas. So far, I am importing data from postgresql in the following fashion and neither leveraging django framework for the calculation, kind of as such: conn = engine.connect() print("engine connected") metadata = sqlalchemy.MetaData() print("metadata acquired") parameters = sqlalchemy.Table('dashboard2_parameters2', metadata, autoload=True, autoload_with=engine) print("histo data loaded") query = sqlalchemy.select([parameters]) print("query done") resultproxy = conn.execute(query) print("resultproxy done") conn.close() result_set = resultproxy.fetchall() dt = pd.DataFrame(result_set) dt.columns = result_set[0].keys() print("parameters", dt) I am wondering if using: dt = parameters2.objects.all() would do the same thing? I am concerned also about speed as some of the table can get pretty big, what would be the trade off in terms of speed of the two techniques? -
Django ManyToMany field on custom column in existing database
I have a database with one table for recipes without the ingredients and one table with the ingredients each with a recipe id to reference each other. Now I don't know how to refer to the recipe id column, because at the moment (I build a rest API) it returns no ingredients. My models.py class Ingredients(models.Model): ingredientid = models.AutoField(db_column='IngredientID', primary_key=True, blank=True) recipeid = models.ForeignKey('Recipe', models.DO_NOTHING, db_column='RecipeID', blank=True, null=True, related_name='+') amount = models.CharField(blank=True, null=True, max_length=100) unit = models.CharField(blank=True, null=True, max_length=100) unit2 = models.CharField(blank=True, null=True, max_length=100) ingredient = models.CharField(db_column='Ingredient', blank=True, null=True, max_length=255) class Meta: managed = False db_table = 'Ingredients' class Recipe(models.Model): recipeid = models.AutoField(db_column='RecipeID', primary_key=True, blank=True) # Field name made lowercase. title = models.CharField(db_column='Title', blank=True, null=True, max_length=255) # Field name made lowercase. preperation = models.TextField(db_column='Preperation', blank=True, null=True) # Field name made lowercase. images = models.CharField(db_column='Images', blank=True, null=True, max_length=255) # Field name made lowercase. ingredients = models.ManyToManyField(Ingredients) class Meta: managed = True db_table = 'Recipes' I hope you understand my problem and can help me. Thank you very much! -
Django send_mail error using smtp.domain.com (smtplib.SMTPHeloError: (501, b'Syntactically invalid HELO argument(s)'))
I have a problem when sending an email using Django as the email I'm trying to send from is hosted on domain.com, I've tried to send from Gmail and it worked fine but when I use the configuration of domain.com it gives me this error: smtplib.SMTPHeloError: (501, b'Syntactically invalid HELO argument(s)') what I understand is that it is related to the host name, but I don't know what to do to fix that error and can I use a different hostname for domain.com that works. below is the configuration in setting.py and send_mail function: setting.py: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.domain.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'ARomayh@endorsefinance.com' EMAIL_USE_TLS = True EMAIL_USE_SSL = False EMAIL_HOST_PASSWORD = "********" send_mail function: send_mail( 'HR Request', 'your request is being processed', 'ARomayh@endorsefinance.com', ['ARomayh@endorsefinance.com'], fail_silently=False, ) return HttpResponse('Mail sent') -
images_data = validated_data.pop('images') KeyError: 'images'
I am trying to upload multiple images to the article as ArrayField(ImageField()) is not working on Django right now. Here are my codes: Models.py class Article(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User,on_delete=models.CASCADE,related_name='articles') class ArticleImages(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) image = models.ImageField(upload_to='images',null=True,blank=True,) article = models.ForeignKey(Article, on_delete=models.CASCADE,null=True,blank=True,related_name='images') Serializers.py class ArticleImagesViewSerializer(serializers.ModelSerializer): class Meta: model = ArticleImages fields = ('id','image') def create(self, validated_data): return ArticleImages.objects.create(**validated_data) class ArticleViewSerializer(serializers.ModelSerializer): images = ArticleImagesViewSerializer(required=False,many=True,allow_null=True) class Meta: model = Article fields = ('id','author','images') def create(self, validated_data): images_data = validated_data.pop('images') article = Article.objects.create(**validated_data) for image_data in images_data: ArticleImages.objects.create(article=article, **track_data) return article Views.py class ArticleView(CreateAPIView): queryset = Article.objects.all() serializer_class = ArticleViewSerializer permission_classes = (AllowAny,) def get(self, request, format=None): queryset = Article.objects.all() serializer = ArticleViewSerializer() return Response(serializer.data) def post(self, request, *args, **kwargs): serializer = ArticleViewSerializer(data=request.data) if serializer.is_valid(): article = serializer.save() serializer = ArticleViewSerializer(article,many=True) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) class ArticleImagesView(CreateAPIView): queryset = ArticleImages.objects.all() serializer_class = ArticleImagesViewSerializer permission_classes = (AllowAny,) def get(self, request, format=None): queryset = ArticleImages.objects.all() serializer = ArticleImagesViewSerializer() return Response(serializer.data) def post(self, request, *args, **kwargs): serializer = ArticleImagesViewSerializer(data=request.data) if serializer.is_valid(): articleimages = serializer.save() serializer = ArticleImagesViewSerializer(articleimages,many=True) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Now i am facing with an issue that gives KeyError: images_data = validated_data.pop('images') KeyError: 'images' … -
hot to write create function for this view in one post form, i want to create with template
enter image description hereand second question: how i post this form from my template (html file) i have two forign key in one model, i cant write create post form as django default admin models.py class Survey(models.Model): GENDER = ( ('male', 'male'), ('female', 'female'), ) full_name = models.CharField(max_length=255) gender = models.CharField(choices=GENDER, max_length=50) room = models.IntegerField() phone = models.CharField(max_length=15) feedback = models.TextField(null=True, blank=True) date_created = models.DateTimeField(auto_now_add=True) def __str__(self): return '{}'.format(self.full_name) class Service(models.Model): service = models.TextField() average = models.FloatField(null=True, blank=True) date_created = models.DateTimeField(auto_now_add=True) def __str__(self): return '{}'.format(self.service) class ServiceEvaluation(models.Model): RANK = ( (1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8, 8), (9, 9), (10, 10), ) survey = models.ForeignKey(Survey, on_delete=models.SET_NULL, null=True) service = models.ForeignKey(Service, on_delete=models.SET_NULL, null=True, related_name='ranks') rank = models.PositiveIntegerField(choices=RANK, default=1) date_created = models.DateTimeField(auto_now_add=True, null=True, blank=True) -
Django: Form default date different on production server
I have a AddRecordTimeFrame form. class AddRecordTimeFrame(forms.ModelForm, OverviewAddTimeframeMixin): start_date = forms.ChoiceField(label='Start Date:',widget=forms.Select(attrs={'style': 'width:140px'}),choices=get_datetime_choices('date'),initial=datetime.date.today()) start_time = TimeFieldHHSS(widget=forms.TimeInput(attrs={'style': 'width:80px;height:23px'})) class Meta: model = RecordModel fields = ('test_cell','start_date','start_time',) labels = RecordModel.RECORD_NAMING_CONV The initial value being datetime.date.today(), returns correctly on my Development server but does not on Production server. But in fact returns the date in which I last restart the server as the initial value (Which was Oct 13 2020). Development Version Production Version I would like to determine the cause of this behavior and how to rectify the issue to allow the current datetime to show as default in the production server. Software Both use same version of source code and requirements versions(Python, Django etc.) Both MariaDB Development Windows 7 Production Linux (Debian) NginX Gunicorn -
Create localized django app and use the localization from other app
I have the following problem: I created a Django app (app1) and then installed it in other one (app2). Now I'm trying to make the internationalization of the site, but I want to be able to use the installed app translations and I cannot even compile them. Some useful information: APP 1 . ├── MANIFEST.in ├── app1 │ ├── admin.py │ ├── apps.py │ ├── forms.py │ ├── __init__.py │ ├── locale/ │ │ ├── en-us │ │ │ └── LC_MESSAGES │ │ │ └── django.po │ │ ├── es │ │ │ └── LC_MESSAGES │ │ │ └── django.po │ │ └── pr │ │ └── LC_MESSAGES │ │ └── django.po │ ├── migrations/ │ ├── models.py │ ├── settings.py │ ├── static/ │ ├── templates │ ├── tests.py │ ├── urls.py │ ├── utils.py │ └── views.py └── setup.py APP 2 (the one that has APP 1 installed) ├── app2/ │ ├── locale/ │ │ ├── en-us/ │ │ │ └── LC_MESSAGES │ │ │ ├── django.mo │ │ │ └── django.po │ │ ├── es/ │ │ │ └── LC_MESSAGES │ │ │ ├── django.mo │ │ │ └── django.po │ │ └── pr/ │ │ └── … -
Group by time period - Django
class Book(models.Model): BOOK_CATEGORY = (('0', 'Romance'), ('1', 'Novel'), ('2', 'Comedy')) price = models.FloatField() category = models.IntegerField(choices=BOOK_CATEGORY) publishing_year = models.DateField() What would be the best way query wise to get the average price of the books with a dynamic period? So average of books sold monthly , quarterly , half year etc.