Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
testdriven.io django tdd - got Error: '$' is not a valid port number when running docker run
Every time I try to run the command docker run --name django-tdd -e "PORT=8765" -p 8008:8765 registry.heroku.com/lit-sierra-68791/web:latest I get Error: '$' is not a valid port number Dockerfile.prod # pull official base image FROM python:3.9.5-slim-buster # set working directory WORKDIR /usr/src/app # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 ENV DEBUG 0 ENV SECRET_KEY fgerg345y4y56u5u5757jk5k56kuykykyk ENV DJANGO_ALLOWED_HOSTS localhost 127.0.0.1 [::1] ENV PORT 8765 # install system dependencies RUN apt-get update \ && apt-get -y install gcc postgresql \ && apt-get clean # add and install requirements RUN pip install --upgrade pip COPY ./requirements.txt . RUN pip install -r requirements.txt # add app COPY . . # add and run as non-root user RUN adduser --disabled-password myuser USER myuser # run gunicorn CMD gunicorn drf_project.wsgi:application --bind 0.0.0.0:$PORT I even added the ENV PORT 8765 in the file above, but it didn't worked too. -
Django ListCreateAPIView not calling get_querryset
Hello I started with Django couple weeks ago, I wanted to return the objects that are closest to the location send in the query parameters. I think that the function get_querryset is never called because it doesn't change anything. These are the files I have: #models.py from django.contrib.gis.db import models class CarOffering(models.Model): name = models.CharField(max_length=200) location = models.PointField(null=True,blank=True) def __str__(self): return self.name #serializer.py from .models import CarOffering from rest_framework import serializers class CarSerializer(serializers.ModelSerializer): distance = serializers.FloatField(source='distance.mi', read_only=True, required=False) class Meta: model = CarOffering fields = ['name','location', 'distance'] read_only_fields = ['location'] #Views.py from .models import CarOffering from django.contrib.gis.geos import GEOSGeometry from django.contrib.gis.db.models.functions import Distance from .serializers import CarOfferingSerializer from django.shortcuts import render from rest_framework.generics import ListCreateAPIView import geocoder class ListCreateCarOffering(ListCreateAPIView): queryset = CarOffering.objects.all() serializer_class = CarOfferingSerializer def get_querryset(self): qs = super().get_querryset() latitude = self.request.query_params.get('lat', None) longitude = self.request.query_params.get('lng', None) if latitude and longitude: pnt = GEOSGeometry('POINT(' + str(longitude) + ' ' + str(latitude) + ')', srid=4326) qs = qs.annotated(distance=Distance('location', pnt)).order_by('distance') return qs #urls.py from django.contrib import admin from django.urls import path from proj.views import ListCreateCarOffering urlpatterns = [ path('admin/', admin.site.urls), path('api/caroffer', ListCreateCarOffering.as_view(),name = 'list_caroffer') When I look in http://127.0.0.1:8000/api/caroffer I get the same thing as if I do http://127.0.0.1:8000/api/caroffer?lat=0&lng=0: [ { … -
Fetch load a page that only shows the Json data instead of the page that should be displayed
I am trying to make a twitter like application for a class project. When the like button is clicked the button should then change to say unlike and the like count should increase without reloading the page. Instead the page reloads to a white background and the only thing on the page is "{"likeButton": "Unlike", "total_likes": 0}" my json data. Any help would be appreciated. views.py @login_required def likes(request, post_id): try: current_user = request.user post = Post.objects.get(id = post_id) likeCount = Post.objects.get(id = post.id) total_likes = likeCount.like_count likeButton = request.POST.get('buttonForLikes') if likeButton == 'Like': total_likes = total_likes + 1 post.like_count = total_likes post.save() post.like.add(current_user) post.save() else: total_likes = total_likes - 1 post.like_count = total_likes post.like.remove(current_user) post.save() return JsonResponse ({'likeButton': likeButton, 'total_likes': total_likes,}, status=200,) except KeyError: return HttpResponseBadRequest("Like Error") urls.py from django.urls import path from . import views app_name = "network" urlpatterns = [ path("", views.index, name="index"), path("login", views.login_view, name="login"), path("logout", views.logout_view, name="logout"), path("register", views.register, name="register"), path("new-post", views.new_post, name="new-post"), path("profile/<str:username>", views.profile, name="profile"), path("follows/<str:username>", views.follows, name="follows"), path("following", views.following, name="following"), path("edit", views.edit, name="edit"), path("likes/<int:post_id>", views.likes, name='likes') ] HTML {% extends "network/layout.html" %} {% load static %} {% block body %} {% if user.is_authenticated %} <div class="borderDiv"> <div class="newPostCard"> <form id = "new_post_form" name="newPost" … -
Django ModelForm: change a field value when blank
Is there any way to change a field value (related to a foreign key) in a Django ModelForm once the form is initialized and filled by the user (I'm using request.POST). I want to change the value when the user doesn't select any option of the dropdown list. I tried this with no result: form.data['field'] = 1 I got this message: This QueryDict instance is immutable I know I can set an initial (default) before introducing data in the form but I don't want to have the default option highlighted in the dropdown. -
Pass kwarg into an inlineformset_factory?
I am trying to pass the request object into my inlineformset_factory and am struggling to accomplish this. In forms.py I have the following: class SummativeScoreForm(forms.ModelForm): """ Form definition for SummativeScore Form """ subdomain_proficiency_level = forms.ModelChoiceField( empty_label="Undecided", queryset=SubdomainProficiencyLevel.objects.none(), widget=forms.RadioSelect, required=False, ) def __init__(self, *args, **kwargs): self.request = kwargs.pop("request", None) super(SummativeScoreForm, self).__init__(*args, **kwargs) if self.instance: if self.request.user == self.instance.summative.employee: self.fields["subdomain_proficiency_level"].disabled = True self.fields[ "subdomain_proficiency_level" ].queryset = SubdomainProficiencyLevel.objects.filter( subdomain=self.instance.subdomain ) self.fields[ "subdomain_proficiency_level" ].label = f""" {self.instance.subdomain.character_code}: {self.instance.subdomain.short_description} """ class Meta: model = SummativeScore fields = "__all__" widgets = { "subdomain_proficiency_level": forms.RadioSelect( attrs={"class": "list-unstyled"} ), } SummativeScoreInlineFormset = inlineformset_factory( Summative, SummativeScore, fields=("subdomain_proficiency_level",), can_delete=False, extra=0, form=SummativeScoreForm, ) I'm using a FormView CBV to show this inline_formset class SummativeScoreFormView( LoginRequiredMixin, UserIsObserverOrObserveeMixin, SingleObjectMixin, FormView, ): model = Summative template_name = "commonground/summative_score_form.html" pk_url_kwarg = "summative_id" def get(self, request, *args, **kwargs): summative_id = kwargs.pop("summative_id") self.object = self.get_object( queryset=Summative.objects.filter(id=summative_id) ) return super().get(request, *args, **kwargs) def post(self, request, *args, **kwargs): summative_id = kwargs.pop("summative_id") self.object = self.get_object( queryset=Summative.objects.filter(id=summative_id) ) return super().get(request, *args, **kwargs) def get_form(self, form_class=None): return SummativeScoreInlineFormset( **self.get_form_kwargs(), instance=self.object ) def get_form_kwargs(self): kwargs = super().get_form_kwargs() kwargs["request"] = self.request return kwargs def form_valid(self, form): form.save() messages.add_message(messages.SUCCESS, "Changes were saved!") HttpResponseRedirect(self.get_success_url()) def form_invalid(self, form): print("invalid form") return super().form_invalid(form) def get_success_url(self): user_id = self.kwargs["user_id"] … -
How to trigger the page reload animation without refreshing?
Any ideas? Image, at least 30 characters -
What does that mean Pending request status in chrome developer tool while login apache based application?
enter image description hereWhile login apache 2.4 based application backend url status shows in pending state in chrome developer tool and not able to proceed further and unable to login application. Also not able to logged error in the apache log file. -
How to calculate average of fields on some if conditions in django?
I am working on Django where I have two models Gigs and Orders and I am calculating average Completion time of order of every gig. in order model I have two fields order start time (which I'm sending whenever seller accepts the order) and order completed time (which I'm sending when seller delivered) the order. but I want to calculate average of only those orders where isCompleted = True Models.py class Orders(models.Model): buyer = models.ForeignKey(User,default=None, on_delete=models.CASCADE,related_name='buyer_id') seller = models.ForeignKey(User,default=None, on_delete=models.CASCADE,related_name='seller_id') item = models.ForeignKey(Gigs,default=None, on_delete=models.CASCADE,related_name='gig') payment_method= models.CharField(max_length=10) address = models.CharField(max_length=255) mobile = models.CharField(max_length=13,default=None) quantity = models.SmallIntegerField(default=1) status = models.CharField(max_length=13,default='new order') orderStartTime = models.DateTimeField(default=timezone.now) orderCompletedTime = models.DateTimeField(default=timezone.now) isCompleted = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) class Gigs(models.Model): title = models.CharField(max_length=255) category = models.ForeignKey(Categories , on_delete=models.CASCADE) images = models.ImageField(blank=True, null = True, upload_to= upload_path) price = models.DecimalField(max_digits=6, decimal_places=2) details = models.TextField() seller = models.ForeignKey(User,default=None, on_delete=models.CASCADE) @property def average_completionTime(self): if getattr(self, '_average_completionTime', None): return self._average_completionTime return self.gig.aggregate(Avg(F('orderCompletedTime') - F('orderStartTime'))) Views.py class RetrieveGigsAPI(GenericAPIView, RetrieveModelMixin): def get_queryset(self): return Gigs.objects.annotate( _average_completionTime=Avg( ExpressionWrapper(F('gig__orderCompletedTime') - F('gig__orderStartTime'), output_field=DurationField()) ) ) serializer_class = GigsSerializerWithAvgTime permission_classes = (AllowAny,) def get(self, request , *args, **kwargs): return self.retrieve(request, *args, **kwargs) Serializers.py class GigsSerializerWithAvgTime(serializers.ModelSerializer): average_completionTime = serializers.SerializerMethodField() def get_average_completionTime(self, obj): return obj.average_completionTime class Meta: model = Gigs … -
I am trying save the Exception to sql lite db in my django project.But getting error
The Exception value is local variable 'func' referenced before assignment when i am trying to save it to db i am getting this error Failure near "func": syntax error Please Help me with this -
Why are django tags causing problems?
Is there any reason why 1st django tag above !DOCTYPE html is causing error and {% comment %} tag is not working at all? I'm working in pycharm. -
Adding features and filtering later on the product model
If I need to explain more clearly compared to the title, there is a table on the database of the Product class created in the models.py file. Is it possible for the user to add a new attribute to this Product table? In other words, the user will add a property called color and assign values to this property, and then filter on it. A system written in PHP called IdeaSoft supports this, but is it possible to do this with Django? Is there a library about it? -
ModuleNotFoundError: No module named 'django_heroku'
i wanted to run my project in server. Well when I start the server I get an error ModuleNotFoundError: No module nameddjango_heroku enter image description here but i don't use heroku thanks for answer -
How to get certain item in Django, def view
pk argument works in class views and I have done it in that way but I am curious can i get certain item in function view in Django? views.py def cart(request): cart = Cart.objects.annotate( price=Sum(F('orderitem__item__price') * F('orderitem__quantity')) ).get(order_user=request.user) cart.total = cart.price cart.save() order_items = OrderItem.objects.filter(cart=cart) context = { 'cart': cart, 'order_items': order_items} if 'checkout' in request.POST: reverse('checkout-page') if 'minus' in request.POST: item = OrderItem.objects.filter(??) item.quantity = F('quantity') - 1 item.quantity.save() return render(request, 'shop/cart.html', context) models.py class OrderItem(models.Model): cart = models.ForeignKey('Cart', on_delete=CASCADE, null=True) item = models.ForeignKey(Item, on_delete=CASCADE, null=True) quantity = models.IntegerField(default=1) total_price = models.IntegerField(default=1) -
Make files public when uploading to AWS S3 bucket from Django
I am working with a basic music streaming application at the moment and would like for all files uploaded to my S3 bucket to have public read access. Right now, when they are uploaded using "upload_to" in a FileField they are not public. How would I adjust my code to make this an automatic process? concert.models from django.db import models from django.db.models import ( CharField, TextField, ForeignKey, BooleanField, DateField, FileField, IntegerField, CASCADE ) import uuid import pdb from django.contrib.auth.models import User from django.utils import timezone from django.utils.timezone import now def user_directory_path(instance, filename): random_file_name = "".join([str(uuid.uuid4().hex[:6]), filename]) return "concerts/{0}/{1}/{2}/{3}/{4}/{5}".format(instance.concert.date.year, instance.concert.date.month, instance.concert.date.day, instance.concert.venue, instance.concert.pk, random_file_name) class Band(models.Model): name = TextField() def __str__(self): return self.name class Concert(models.Model): venue = TextField() date = DateField() city = CharField(null=True, blank=True, max_length=100) state = CharField(null=True, blank=True, max_length=100) country = TextField() band = ForeignKey(Band, on_delete=CASCADE, related_name='concert') user = ForeignKey(User, on_delete=CASCADE, related_name='concert') date_created = DateField(default=now) def save(self, *args, **kwargs): '''On save, update timestamps ''' if not self.id: self.date_created = timezone.now() return super(Concert, self).save(*args, **kwargs) def __str__(self): return self.venue class Song(models.Model): title = TextField() concert = ForeignKey(Concert, on_delete=CASCADE, related_name='song') user = ForeignKey(User, on_delete=CASCADE, related_name='song', null=True, blank=True) concert_order = IntegerField(null=True, blank=True) audio_file = models.FileField("Song", upload_to=user_directory_path, null=True) date_created = DateField(default=now) def save(self, … -
How to add view count everytime endpoint get request accessed
I'm building a REST API with Django rest framework. One of the models : class Feed(models.Model): id = models.BigAutoField(primary_key=True) title = models.CharField(max_length = 200) content = models.TextField() thumbnail = models.ImageField(upload_to=get_profile_image_filepath, default='uploads/feed/index.jpg', blank=True) imgpath = models.CharField(max_length = 200, blank=True, default=timestr) author = models.CharField(max_length = 100) date = models.DateTimeField(auto_now_add=True) view = models.IntegerField(default=0) I want the feed view added when the user accessed the endpoint. views.py class FeedDetail(generics.RetrieveAPIView): queryset = Feed.objects.all() serializer_class = FeedSerializer urls.py path('feeds/<int:pk>/', FeedDetail.as_view()), -
How to set a proxy model for select related in Django?
I have two models: class Parent(models.Model): some_field = models.CharField(max_length=50, default='') class Child(models.Model): parent = models.ForeignKey(Parent) And two proxy models for Parent: class ProxyParentFirst(Parent): class Meta: proxy = True class ProxyParentSecond(Parent): class Meta: proxy = True How to set proxy model of Parent in select related for Child: children = Child.objects.all().select_related('ProxyParentFirst') or children = Child.objects.all().select_related('ProxyParentSecond') -
Adding to manytomany field returns empty queryset
I am trying to add items in the many-to-many field. After adding it, I am getting an empty queryset. It taking me crazy. if request.user.is_authenticated: order = Order.objects.create(restaurant=Restaurant.objects.get(code_name=restaurant_code), table=Table.objects.get(code_name=request.data['table']), customer=request.user ) else: order = Order.objects.create(restaurant=Restaurant.objects.get(code_name=restaurant_code), table=Table.objects.get(code_name=request.data['table']) ) for menuitem in request.data['menuItems']: customList = [ItemType.objects.get(id=v) for v in list(menuitem['addOns'])] orderedMenuItem = OrderedMenuItem.objects.create(quantity=menuitem['quantity'], menuitem=MenuItem.objects.get(pk=menuitem['id']), remarks=menuitem['remarks']) orderedMenuItem.custom_item_types.add(*customList) order.ordered_menu_items.add(orderedMenuItem) order.save() Here I have ItemType as manytomany field got orderedMenuItem model. When trying to add ItemType object into OrderedMenuItem model, its giving empty query set. -
MyModelAdmin must have search_fields for the autocomplete_view
I have 404 in Admin suggest with error ApartmentPromotionAdmin must have search_fields for the autocomplete_view. My admin organized as follows from string import Template from dal import autocomplete from django import forms from django.contrib import admin from django.contrib.admin.widgets import AutocompleteSelect from django.forms import widgets class PromotionApartmentForm(forms.ModelForm): class Meta: fields = "__all__" widgets = { "apartment": AutocompleteSelect( ApartmentPromotion._meta.get_field("apartment").remote_field, admin.site, attrs={"style": "width: 400px"}, # You can put any width you want. ), } class ApartmentPromotionAdmin(admin.ModelAdmin): form = PromotionApartmentForm list_display = ("id", "apartment") autocomplete_fields = ["apartment"] I have admin.site.register(ApartmentPromotion, ApartmentPromotionAdmin) and models are class ApartmentPromotion(models.Model): apartment = models.ForeignKey(Apartment, on_delete=models.CASCADE, related_name="promotions") ... def __str__(self): return f"<{self.id}> {self.apartment} {self.status}" class Meta: indexes = [ models.Index(fields=["id"]), models.Index(fields=["apartment_id"]), ] class Apartment(models.Model): owner = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name="owned_apartments") .... class Meta: indexes = [ models.Index(fields=["owner_id"]), ] could you help me to fix the problem ? -
Update Task APIView' object has no attribute 'action'
I m totally new in django and rest. I wanna write a program that only lets the owner update or delete his tasks. When I try to use it, it doesn't prohibit me to update or delete (others tasks) and when I press the update or delete button it returns me this error "Update Task APIView' object has no attribute 'action'" Thanks for helping models.py class Task(models.Model): title=models.CharField(max_length=250) text=models.TextField() user=models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=False) status=models.ForeignKey('Status',on_delete=models.SET_NULL,null=True) startDate=models.DateTimeField(auto_now_add=True) endDate=models.DateField(null=True) def __str__(self): return self.title class Status(models.Model): name=models.CharField(max_length=250) def __str__(self): return self.name Permissions.py: from rest_framework import permissions class IsOwner(permissions.BasePermission): def has_object_permission(self, request, view,obj): if (obj.user == request.user) | (view.action == 'retrieve'): return True else: return False Serializers.py: from rest_framework import serializers from .models import Task,Status class TaskSerializer(serializers.ModelSerializer): class Meta: model = Task # fields = ['title', 'text', 'status', 'endDate'] fields = '__all__' class StatusSerializer(serializers.ModelSerializer): class Meta: model = Status fields = '__all__' Views.py class TaskViewSet(ModelViewSet): """ API endpoint that allows users to be viewed or edited. """ queryset = Task.objects.all() serializer_class = TaskSerializer permission_classes = [permissions.IsAuthenticated, IsOwner,] def perform_create(self, serializer): serializer.save(user=self.request.user) class ListTaskAPIView(generics.ListAPIView): serializer_class = TaskSerializer permission_classes = [IsAuthenticatedOrReadOnly] model= Task def get_queryset(self): """ Optionally restricts the returned purchases to a given user, by filtering against … -
Do you need to know how to design a database before you can create a good django model?
Do django developers draw a database architecture before they code it in the models.py? If yes , does it mean you have to be good in database design before you can create a good database-driven website? If yes where do I get to learn database design? -
django many-to-many-field in list display for item like count
I want to display total likes against each item in Django admin list_display. The many to many field is linked with the user model. Below is my code Model: class Item(models.Model): title = models.CharField(max_length=100) description= RichTextField(blank=True, null=True) main_image= models.ImageField(null=False, blank=False,upload_to='images/') upload = models.FileField(upload_to ='uploads/') date = models.DateTimeField(auto_now_add=True) item_category = models.ForeignKey(Categories, default='Coding', on_delete=SET_DEFAULT) item_tool = models.ForeignKey(Tools, default='XD', on_delete=SET_DEFAULT) slug = models.SlugField(unique=True, blank=True, null=True) # new author = models.ForeignKey(User, on_delete=models.CASCADE) likes = models.ManyToManyField(User, related_name='post_likes') def total_likes(self): return self.likes.count() Admin.py from django.contrib import admin from .models import Categories, Item, Tools class ItemAdmin(admin.ModelAdmin): list_display = ('title','author','item_category','date') list_filter = ('item_category',) admin.site.register(Categories) admin.site.register(Item, ItemAdmin) admin.site.register(Tools) -
Can't login in Django project after switching to django 3 and return to django 2
I have a Django 2.2 project that runs in a bunch of different servers, but they use the same database. I've created a branch to migrate to Django 3, but not all servers will be migrated at the same time. I use Argon2: # https://docs.djangoproject.com/en/dev/ref/settings/#password-hashers PASSWORD_HASHERS = [ 'django.contrib.auth.hashers.Argon2PasswordHasher', 'django.contrib.auth.hashers.PBKDF2PasswordHasher', 'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher', 'django.contrib.auth.hashers.BCryptSHA256PasswordHasher', 'django.contrib.auth.hashers.BCryptPasswordHasher', ] When I switched to django 3.2 in my developing branch everything worked fine. But then, when I returned to Django 2.2, I started getting errors like: Template syntax error Incorrect padding (exception location: .../python3.6/base64.py in b64decode) Those problems where solved by just deleting the cookies and reloading. So I guessed that they were related to the change in django 3.1 to a new default hashing algorithm from sha1 to sha256. Anyway, after reloading, the page worked. But when I tried to login it didn't recognize the credentials. Then I restored the database from backup and could login in django 2.2. I tried again to run on django 3.2 with the setting: DEFAULT_HASHING_ALGORITHM = 'sha1' Now, when switching back to 2.2, I didn't get errors on page load (I didn't need to delete cookies) but the credentials still didn't work. For me it looks like after switching … -
Django model how to do many to one mapping?
I am trying to map multiple field to same field in vendor and menu class. If I map using foreign key like below it works. But this is not what I want. class OrderItem_Mon(models.Model): vendor_name = models.ForeignKey(Vendor, on_delete=models.SET_NULL, null=True) menu_name = models.ForeignKey(Menu, on_delete=models.SET_NULL, null=True) date_created = models.DateTimeField('date created', auto_now_add=True) note = models.CharField('note', max_length=255, null=True, blank=True) I need to map multiple field to same field of specific table like this. class OrderItem_Mon(models.Model): vendor_name_1 = models.ForeignKey(Vendor, db_column='vendor_name', on_delete=models.SET_NULL, null=True) menu_name_1 = models.ForeignKey(Menu, db_column='menu_name',on_delete=models.SET_NULL, null=True) vendor_name_2 = models.ForeignKey(Vendor, db_column='vendor_name',on_delete=models.SET_NULL, null=True) menu_name_2 = models.ForeignKey(Menu, db_column='menu_name', on_delete=models.SET_NULL, null=True) date_created = models.DateTimeField('date created', auto_now_add=True) note = models.CharField('note', max_length=255, null=True, blank=True) However, it does not work. How do I make this work? Basically, I need to make new form that have dropbox that gets value from vendor and menu model to each field. Help -
Django: I want to create a self-generated code based on previous records and a sequential number
I'm a coding noob and I'm writing a website in Django for Project and task management, and I want to generate a project code field in a 'Project' model automatically based on previous records. I was thinking to make the 'project code' a CharField which must have 3 parts: 'department code', a foreign key of a 'Department' model with its own 'name' and 'code' fields, from which I only need the 2-3 letter code value, a 'year' code based on project start date using the last 2 digits of the date's year, and a sequence code which should be the last record based on the above filters +1. The project code field should look like this: DDD-YY-SS, where DDD is department code, YY is 2-digit year number and SS the sequence number. I'm trying to include the code generator in a custom save method like this: def save(self, *args, **kwargs): dpt = str(self.department.code) project_date = self.projectdate yy = str(project_date.year)[-2:] filter_kw = '{}-{}-'.format(dpt, yy) lastrec = ProjectModel.objects.filter(project_code__startswith = filter_kw).last() if lastrec == None: lastrec = '00' else: lastrec = str(lastrec.project_code)[-2:] newnum = "{:02d}".format(int(lastrec)+1) self.code = '{}-{}'.format(filter_kw, str(newnum)) super(ProjectModel, self).save(*args, **kwargs) But I think this code is... sketchy? I feel like using … -
Django race condition aggregate(Max) in F() expression
Imagine the following model: class Item(models.Model): # natural PK increment = models.PositiveIntegerField(_('Increment'), null=True, blank=True, default=None) # other fields When an item is created, I want the increment fields to automatically acquire the maximum value is has across the whole table, +1. For example: |_item____________________________| |_id_|_increment__________________| | 1 | 1 | | 2 | 2 | | 4 | 3 | -> id 3 was deleted at some stage.. | 5 | 4 | | 6 | 5 | .. etc When a new Item() comes in and is saved(), how in one pass, and in way that will avoid race conditions, make sure it will have increment 6 and not 7 in case another process does exactly the same thing, at the same time? I have tried: with transaction.atomic(): i = Item() highest_increment = Item.objects.all().aggregate(Max('increment')) i.increment = highest_increment['increment__max'] i.save() I would like to be able to create it in a way similar to the following, but that obviously does not work (have checked places like https://docs.djangoproject.com/en/3.2/ref/models/expressions/#avoiding-race-conditions-using-f): from django.db.models import Max, F i = Item( increment=F(Max(increment)) ) Many thanks