Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I send response data form multiple tables via django rest framework
I want to send Response(xyzSerializer.data), where xyzSerializer serializes data form two models i.e. Users and Customers to give it following body/look { 'userID': 1, 'firstName': 'name', 'lastName': 'Lname', 'gender': 'Male', 'country': 'Cloc', 'city': 'City', 'phoneNumber': '12345', 'dob': 'dd-mm-yy', 'dateJoined': 'dd-mm-yy', 'role': 'blogger', 'user': 1 'customerID': 1, 'occupation': '', 'blogger': True, 'userID': 1 } But, currently I can either serialize Users, or Customers model individually which give following output respectively, UserSerializer { 'userID': 1, 'firstName': 'name', 'lastName': 'Lname', 'gender': 'Male', 'country': 'Cloc', 'city': 'City', 'phoneNumber': '12345', 'dob': 'dd-mm-yy', 'dateJoined': 'dd-mm-yy', 'role': 'blogger', 'user': 1 } CustomerSerializer { 'customerID': 1, 'occupation': '', 'blogger': True, 'userID': 1 } I want to join data from two models using userID and send that as a response. Here are my Users and Customers models, class Users(models.Model): userID = models.AutoField(primary_key=True) user = models.OneToOneField(User, on_delete=models.CASCADE) firstName = models.TextField() lastName = models.TextField() gender = models.TextField() country = models.TextField() city = models.TextField() phoneNumber = models.TextField() dob = models.TextField() dateJoined = models.TextField() role = models.TextField() def __str__(self): return f"ID: {self.userID}" class Customers(models.Model): customerID = models.AutoField(primary_key=True) userID = models.ForeignKey('Users', on_delete=models.CASCADE, name="userID") occupation = models.TextField() blogger = models.BooleanField(default= False) def __str__(self): return f"ID: {self.customerID}" Here are my Serializers, class UserSerializer(ModelSerializer): class Meta: model … -
DRF normalize nested serializer
I have a ManyToMany field in my models. In serializer, I am able to get the nested serialized data, but I want to normalize it. models.py class Authors(models.Model): name = models.CharField(max_length=20) class Mets: db_table = "authors" class Books(models.Model): book_name = models.CharField(max_length=100) authors = models.ManyToManyField(Authors, related_names="books") class Meta: db_table = "books" serializers.py class AuthorSerializer(serializer.ModelSerializer): name = serializer.CharField() class Meta: model = Authors field = ("name",) class BooksSerializer(serializer.ModelSerializer): authors = AuthorSerializer() class Meta: model = Books field = ("book_name", "authors") The output of the above will be: "result": [ { "book_name": "Sample", "authors": [ { "name": "Person 1", }, { "name": "Person 2", } ] } ] But I want to output something like this: "result": [ { "book_name": "Sample", "author_name": "Person 1", }, { "book_name": "Sample", "author_name": "Person 2", }, ] -
django s3direct file upload working through admin panel but not through model form
I have a model form that lets users upload images. But when we click submit on that form, it's not being uploaded into s3. I have registered the same model in admin and the upload works through admin panel. So I know my s3 has been configured properly. I have made it to return a Httpresponse called error when the form is invalid and it's returning that when I click submit I am very new to django and can't wrap my head around this. Appreciate any help. Thank You My Model class advert(models.Model): category_choices = ( ("choice", "choice"), ) name = models.CharField(max_length=32) part_name = models.CharField(max_length=50, blank=True) category = models.CharField(choices=category_choices, max_length=255) photo = S3DirectField(dest='primary_destination') seller = models.ForeignKey(User, on_delete=models.CASCADE) soldby = models.CharField(max_length=32, blank=True) place = models.CharField(max_length=32, blank=True) cell = models.CharField(max_length=13,blank=True) My Model Form class advertform(forms.ModelForm): def __init__(self, *args, **kwargs): super(advertform, self).__init__(*args, **kwargs) self.fields['seller'].widget.attrs['hidden'] = True soldby = forms.CharField(widget=forms.TextInput(attrs={'readonly': 'readonly', 'class':'inpt'})) place = forms.CharField(widget=forms.TextInput(attrs={'readonly': 'readonly', 'class':'inpt'})) cell = forms.CharField(widget=forms.TextInput(attrs={'readonly': 'readonly', 'class':'inpt'})) # photo = forms.URLField(widget=S3DirectWidget()) name = forms.CharField(widget=forms.TextInput(attrs={'class': 'inpt', 'placeholder': 'Name of component'})) part_name = forms.CharField(widget=forms.TextInput(attrs={'class': 'inpt', 'placeholder': 'Part no./name'})) class Meta: model = advert fields = ('name', 'part_name', 'category', 'photo', 'soldby', 'place', 'cell', 'seller') My views function def addpost(request): if not User.is_authenticated: … -
change CORS port dynamically
I want to give front access to my endpoints, but their ports range from 3000 to 3005 how can i set that dynamically or set those all CORS_ALLOWED_ORIGINS = [ 'http://localhost:3001', 'http://localhost:3000', ] -
local variable 'Facility' referenced before assignment?
I am facing "local variable 'Facility' referenced before assignment". Although I have imported it from Models. I did same thing for many other models to fetch data but this time it gives this error. Please Assist. Views.py def addshift(request): facilities=Facility.objects.order_by('id') user=request.user if request.method=="POST": StartTime=request.POST.get('StartTime') StartDate=request.POST.get('StartDate') EndTime=request.POST.get('EndTime') EndDate=request.POST.get('EndDate') Facility=request.POST.get('Facility') Note=request.POST.get('Note') shift=Shift(user=request.user,StartTime=StartTime,StartDate=StartDate,EndTime=EndTime,EndDate=EndDate,Facility=Facility,Note=Note) shift.save() messages.success(request,"Shift added successfully!") context={ 'schedule':'active', 'facilities':facilities, 'user':user, } return render(request,'addshift.html',context) Models.py class Facility(models.Model): Title=models.CharField(max_length=200,null=True) FirstName=models.CharField(max_length=200,null=True) LastName=models.CharField(max_length=200,null=True) FacilityName=models.CharField(max_length=200,null=True) FacilityType=models.CharField(max_length=200,null=True) CorporateGroup=models.CharField(max_length=200,null=True) LegalName=models.CharField(max_length=200,null=True) Email=models.CharField(max_length=200,null=True) Phone=models.CharField(max_length=200,null=True) FacilityAddress=models.CharField(max_length=200,null=True) def __str__(self): return self.Title + " | " + self.FacilityAddress -
Getting query of commenter Not request.user
I am building a BlogApp and I am trying to get user of commenter not the request.user, I am building a query of Tag in which i will work on comment's user but it is getting `request.user. models.py class Blog(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=1000) tags = TaggableManager() class Comment(models.Model): commented_by = models.ForeignKey(User, on_delete=models.CASCADE) blog_of = models.ForeignKey(Blog, on_delete=models.CASCADE) body = models.CharField(max_length=1000) views.py def blog_detail_view(request, blog_id): post = get_object_or_404(Blog, pk=blog_id) # Tag query tag = Tag.objects.filter(blog__comment__commented_by=request.user) context = {'post':post} return render(request, 'detail.html', context) What have i tried ? I have also tried tag = Tag.objects.filter(blog__comment__commented_by=post.comment_set.commented_by) But it is not getting the comment user, It is only getting request.user. And if a user commented multiple times than it will get the user also Any help would be much appreciated. Thank You -
Custom user_id Model Field in Django?
For quite some time, i'm having a lot of trouble for creating a custom Model Field in django. Django Autofield provides an automatic assignment of integers like 1, 2, 3, 4, .... But I want to store these numbers like a unique id. example - cs000001, cs000002, cs000003, .... I want cs as a suffix, then a 6 digit number. And I want to do it using a custom model field in django, cause I'll use it as a login field for my User model. Can someone help? -
Allow users to sort in ascending order using radio button django
I have a web page as shown below, the web page able to display the data in the form of a table, I have also implemented the search bar and the page filter and is both working, right now I am try to allow the users to sort the data in ascending order. For example, the customer name will start from A (Airasia) to Z(Zasia) and the part number will start from 1(01232) to 9(999). How do i do that and also at the same time when it is sort in ascending order, both the search bar and the filter pages is also working. views.py @login_required() def ViewMCO(request): search_post = request.GET.get('q') if (search_post is not None) and search_post: allusername = Photo.objects.filter(Q(reception__icontains=search_post) | Q(partno__icontains=search_post) | Q( Customername__icontains=search_post) | Q(mcoNum__icontains=search_post) | Q(status__icontains=search_post) | Q(serialno__icontains=search_post)) if not allusername: allusername = Photo.objects.all().order_by("-Datetime") else: allusername = Photo.objects.all().order_by("-Datetime") page = request.GET.get('page') paginator = Paginator(allusername, 6) try: allusername = paginator.page(page) except PageNotAnInteger: allusername = paginator.page(1) except EmptyPage: allusername = paginator.page(paginator.num_pages) context = {'allusername': allusername, 'query': search_post} return render(request, 'ViewMCO.html', context) ViewMCO.html {% extends "customerbase.html" %} {% block content %} <style> table { border-collapse:separate; border:solid black 1px; border-radius:6px; -moz-border-radius:6px; } td, th { border-left:solid black 1px; border-top:solid black … -
Is it possible to set the related_name field from an abstract class to an instance variable in Django?
In Django, I have an abstract class: class AbstractResult(models.Model): specimen = models.ForeignKey(Specimen, on_delete=models.CASCADE, related_name='%(class)s') ... class Meta: abstract = True This gives me some control over the related name of this field for each concrete class, but not full control. I'd like to be able to set this name in each concrete class. I thought maybe I could use a callable: class AbstractResult(models.Model): def get_related_name(self): raise NotImplementedError("Override this method in your concrete model classes!") specimen = models.ForeignKey(Specimen, on_delete=models.CASCADE, related_name=get_related_name) But that didn't work, as the related_name arg doesn't take a callable. I also thought maybe I could do: class AbstractResult(models.Model): related_name = 'OVERRIDE THIS ATTRIBUTE!' specimen = models.ForeignKey(Specimen, on_delete=models.CASCADE, related_name=related_name) and then try to use it in the concrete class: class TestA_Result(AbstractResult): related_name = "test_a_results" but that didn't work either. Why didn't that work? Is there any simple way to make it work? -
Django Rest framework router ModelViewSet
I want to use ModelViewSet in router. But I want to choose list retrieve destroy. views class UsersView(ModelViewSet): ... I know it can views class UsersView(mixins.RetrieveModelMixin, mixins.DestroyModelMixin, mixins.ListModelMixin, GenericViewSet): ... urls router = DefaultRouter() router.register(r'users', UsersView) urlpatterns += router.urls Is there a better way? -
AttributeError: module 'django.db.models' has no attribute 'BigAutoField'
so i'm following the Django project in the textbook "Python crash course 2nd ed" and i'm into the mapping URLS section for those who know, and when i try my system cant seem to runserver anymore, i'm encountering the following error: AttributeError: module 'django.db.models' has no attribute 'BigAutoField' if anyone can help, it would be great, thanks already. i'm fairly new to django and trying my way around it but i don't really know what or where to find the error.. it worked actually fine before i added the two urls.py: from django.urls import path, include from django.contrib import admin urlpatterns = [ path('admin/', admin.site.urls), path('', include('learning_logs.urls'), name='learning_logs'), ] and """Defines url patterns for learning_logs.""" from django.urls import path from . import views app_name = 'learning_logs' urlpatterns = [ # Home page. path('', views.index, name='index'), ] -
Django Rest Framework Jwt + router
I want the front end to display token and refresk url. Is there a way to add Jwt in the router? I now use urlpatterns = [ path('token/', TokenObtainPairView.as_view(), name='my_jwt_token'), path('refresh/', TokenRefreshView.as_view(), name='token_refresh'), ] I want to do something like this. router = DefaultRouter() router.register(r'token', TokenObtainPairView) router.register(r'token', TokenRefreshView) urlpatterns += router.urls -
If i have many different virtual enviroments in my computer, how to make sure a django project is using a specfic one of them?
Think I have established 5 virtual enviroments in a folder using commandlines, and than start a django project outside of the folder how can i make sure which virtual env i am using in this django project, if the project is not using any virtual env in the folder, how can i change (make some configurations) the project's virtual env to a specific one in the folder? pycharm pro will automaticlly establish the link between django project and virtual env, but what if i am using a community version, how can i make it clear that which django project is using which virtual env? I think i have the same problem in this question from stackoverflow: How to make sure that my django project is using virtual environment that i created for it? if anyone know this and could give me some explaination that would be great, thank a loooooot ahead~ -
Add model data to anohter model with 2 forms in same html with django
Im new in Django and im stuck in one of the main features of a small project im working in, in a few words this is like an ecommerce webpage where users can create lists or categories and then create and add products to them, in the publish template where I'm stuck the user can do all of that, if the user doesn't have a list he can create one with a popping modal or select where he wants to add the product, this is the layout, so you can get a better idea! html publish layout Next i share my model.py code segment: class List(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=40 class Product(models.Model): list = models.ForeignKey(List, on_delete=models.CASCADE) title = models.CharField(max_length=40) description = models.TextField() price = models.IntegerField() My forms.py code segment : class NewList(ModelForm): class Meta: model = List fields = ['title'] class NewProduct(ModelForm): class Meta: model = Product fields = ['title', 'description', 'price'] And finally my views.py segment, which only allows me to create a list: @login_required(login_url='log') def test(request): data = List.objects.filter(user=request.user) listForm = NewList(request.POST) if listForm.is_valid(): l = listForm.save(commit=False) l.user = request.user l.save() context = { 'data': data, 'listForm': listForm } return render(request, "test.html", context) I already … -
Why is django returning my html code when using a variable with the value retained from a filter?
im a beginner at learning django and i have a website with a part that allows you to list down your uncompletetd task so far i only want to display it and whenever i use filter with this second variable({"items":todos} that i want to be displayed in the template it returns the html skeleton *Everything works fine when i dont add this variable in the return statement.I have even tried printing the result from the filter and it works perfectly def dashboard(response): print(response.user.username) if response.method == 'POST': form = CreateNewList(response.POST) if form.is_valid(): n = form.cleaned_data['name'] t = ToDoList(name=n) t.save() response.user.todolist.add(t) else: form = CreateNewList() todos = ToDoList.objects.filter(user=response.user) print(todos) return render(response, 'classy_main/dashboard.html',{"items": todos},{"form":form}) return render(response, 'classy_main/dashboard.html',{"form":form, "list": t}) -
Cant update specific quantity in Django shopping cart
I am trying to update my shopping cart to a specific value that is being passed in by a form under the name "num". I am not sure how I can take this value and update my cart to a specific number. I also have an add to cart button on my mainpage that doesnt include a number input. videogame.html <form action="{% url 'add-to-cart' videogame.pk%}" method='get'> <input name='num' type="number" placeholder="Select Amount" value=1> <a href="{% url 'add-to-cart' videogame.pk%}"> <button class='button submit'>Add to Cart</button> </a> </form> views.py def add_to_cart(request, pk): number = 0 if request.GET.get('num'): number = request.GET.get('num') print(number) videogame = get_object_or_404(Videogame, pk=pk) order_item, created = OrderItem.objects.get_or_create( videogame=videogame, user=request.user, complete=False) order_qs = Order.objects.filter( user=request.user, complete=False) if order_qs.exists(): order = order_qs[0] if order.items.filter(videogame__pk=videogame.pk).exists(): order_item.quantity += 1 order_item.save() else: order.items.add(order_item) else: order = Order.objects.create(user=request.user) order.items.add(order_item) return redirect('cart') -
Django queryset order by another model field without foreignkey
I want Foo.objects.all() order by Bar.order Two tables connect by ryid fields without foreign key. The database I got like this, I cannot set ryid it to foreign key. class Foo(models.Model): lsid = models.AutoField(db_column='Lsid', primary_key=True) ryid = models.IntegerField(db_column='Ryid', blank=True, null=True) class Bar(models.Model): lsid = models.AutoField(db_column='Lsid', primary_key=True) ryid = models.IntegerField(db_column='Ryid', blank=True, null=True) order = models.IntegerField(db_column='Wzpx', blank=True, null=True) -
Django forms - can I post objects to a form, import the form to Views, and re-use it by calling from other functions?
1. Summarize the problem: I am building a Django application, and I'm hoping to create objects that I can post to a form. I envision then importing Forms to Views in Django, and then passing the object to another web page via a definition in Views. 2. Describe what you’ve tried. I'm still in the planning stage, though I've tried a few versions of this with URLs and text. I've been able to create a form to upload new items to a list, for example, and then post that to another web page. 3. When appropriate, show some code. I envision something like the below, but before I get too far down the road, I'd like some expert eyes and advice: def metrics(request, pkid): chart = Metricspage.objects.get(pk=pkid) return render(request, "MyApp/reports/metrics.html", {"chart": chart}) -
Django DetailView: switches me to a different user
I have two user types, a student and a tutor.. and I have this ListView of tutors rendering their name, profile headline and bio, which works successfully, and I also put a link to those three fields redirecting to the detailed view of their profile. Now, I used cbv DetailView for rendering a detailed view of their profile, which also works fine.. but the only problem is, whenever I click on those link as a student, it switches my profile or my user type to that specific tutor, but when I click home or any pages of the website it switches back to normal. Could someone help me with this, please? Because I have search a solution for this problem since yesterday but I couldn't find a problem that similar to mine. Sorry for my english btw. This is the list of tutors, and as you can see on the upper right, I am logged in as a student. Here, you can see on the upper right that it switches me to joss's profile. this is my models class User(AbstractUser): is_student = models.BooleanField(default=False) is_tutor = models.BooleanField(default=False) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) email = models.EmailField(max_length=100) phone_number = models.CharField(max_length=11, blank=False) current_address … -
how to configure django-redis and django
I am working on an ec2 instance ubuntu and i installed redis normally and it works. Now the issue is that i subscribed for redis paid version and created a database on their website redis.com, after creating the database they gave me an endpoint url that look like this redis-21890.us-xx.ec2.cloud.redislabs.com:21890. Using the default config below, django works fine... settings.py CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379/1", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", } } } but i want to connect to the database i paid for so i changed it to CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://redis-21890.us-xx.ec2.cloud.redislabs.com:21890/", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", "PASSWORD": "redisDatabasePassord", } } } and now django is failing with the error below: redis.exceptions.AuthenticationError: Authentication required Is there something that i am doing wrong here? because when i try to connect to the redis-cli -p port -h host -a password with the same credentials it works. -
URL lookup not working with update and retrieve
In the url /users/*username I should be able to access each user by its username, the problem is that it isn't working how it's supposed to, doesn't matter what I write in *username it will update/delete the current logged user. Here it's the User View with the methods that are not working the way I intended: class UserViewSet(mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin, viewsets.GenericViewSet): serializer_class = UserSerializer lookup_field = 'username' queryset = User.objects.all() def get_permissions(self): if self.action in ['signup', 'login',]: permissions = [AllowAny] elif self.action in ['retrieve', 'update', 'destroy']: permissions = [IsAuthenticated, IsSameUser] else: permissions = [IsAuthenticated] return [p() for p in permissions] def retrieve(self, request, *args, **kwargs): response = super(UserViewSet, self).retrieve(request, *args, **kwargs) data = response.data return Response(data=data, status=status.HTTP_200_OK) def update(self, request, *args, **kwargs): serializer = UserModelSerializer(request.user, data=request.data, partial=True) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) -
How to construct an autocomplete page field based on Pint's units and prefixes
I want to be able to enter "Mpa" in a page field and have "MegaPascal" returned as an autocomplete selectable item using Pint's ureg units and prefixes. The main issue is that MegaPascal isn't an actual ureg element, it's the "Mega" prefix combined with the "Pascal" ureg unit. I assume that pint's ureg unit names and abbreviations can be loaded into a Javascript arrays via an api url when the page loads These arrays could then be searched JQuery UI autocomplete using a function as the source. But I can't see how to extract Pint's prefixes from Pint or how to integrate them into the autocomplete source function lookup. My current solution is to load all pint units and abbreviations into a Django model and use django's autocomplete function. -
adding table with Django and report lab
The following code works for pdf creation, what I wanted is put the data to a table def pdf_view(request): enc = pdfencrypt.StandardEncryption("pass", canPrint=0) buf = io.BytesIO() c = canvas.Canvas(buf, encrypt=enc) width, height = A4 textob = c.beginText() textob.setTextOrigin(inch, inch) textob.setFont("Helvetica", 14) lines = [] users = User.objects.filter(is_staff=False) for user in users: lines.append(user.username) lines.append(user.email) lines.append(user.first_name) for line in lines: textob.textLine(line) c.drawText(textob) c.showPage() c.save() buf.seek(0) return FileResponse(buf, as_attachment=True, filename='users.pdf') I tried to append the data to a table, what I tried is as follows def pdf_view(request): enc = pdfencrypt.StandardEncryption("pass", canPrint=0) buf = io.BytesIO() c = canvas.Canvas(buf, encrypt=enc) width, height = A4 textob = c.beginText() textob.setTextOrigin(inch, inch) textob.setFont("Helvetica", 14) lines = [] users = User.objects.filter(is_staff=False) for user in users: lines.append(user.username) lines.append(user.email) lines.append(user.first_name) table = Table(lines, colWidths=10 * mm) table.setStyle([("VALIGN", (0, 0), (-1, -1), "MIDDLE"), ("ALIGN", (0, 0), (-1, -1), "CENTER"), ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black)]) table.wrapOn(c, width, height) table.drawOn(c, 0 * mm, 5 * mm) styles = getSampleStyleSheet() ptext = "This is an example." p = Paragraph(ptext, style=styles["Normal"]) p.wrapOn(c, 50 * mm, 50 * mm) # size of 'textbox' for linebreaks etc. p.drawOn(c, 0 * mm, 0 * mm) # position of text / where to draw c.save() buf.seek(0) return FileResponse(buf, … -
Django: pass information between apps
I've two models in two different apps, In the firs one I'm asking my user biography information in the second one they have question to answer. I'd like to save in my database not only the answers but also the id code created in the account models file and use the userinformation answer to create the string name to use in the database but it gives me error "'ImportError: cannot import name 'name' from 'accounts.models' " even if I've imported the modules- This is my code: **accounts.models** class UserInformation(models.Model): name = models.CharField(max_length=250) lastname = models.CharField(max_length=250) phone = models.CharField(max_length=250) birthday = models.DateField() age = models.CharField(max_length=2) id = models.CharField(max_length=250) def __str__(self): self.name + '_' + self.lastname + '_' + str(self.birthday.year) if self.id_code =="": self.id_code = self.name + '_' + self.lastname + '_' + str(self.birthday.year) self.save() super(UserInformation, self).save(*args, **kwargs) **accounts.forms.py** class UserInformationForm(forms.ModelForm): class Meta: model = UserInformation fields = ('name', 'lastname', 'birthday', 'phone') **accounts.views.py** def add_information(request): if request.method == 'POST': form = UserInformationForm(request.POST, request.FILES) if form.is_valid(): form.instance.user = request.user form.save() return redirect('home') else: form = UserInformationForm() return render(request, 'add_information.html', {'form': form}) **question.models.py** from accounts.models import name class QuestionOne(models.Model): question_1a = models.CharField(max_length=250, choices=point) question_2a = models.CharField(max_length=250, choices=point) question_3a = models.CharField(max_length=250, choices=point) id_code = models.CharField(max_length=250) … -
In Django Admin changelist view, how to make a foreign key column sort by a value other than primary key?
I have a table with a Many-to-One relationship to itself, facilitating a tree structure: class Medium(models.Model): label = models.CharField(max_length=30) parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True) def __str__(self): return self.label In the Django Admin changelist view, I would like show a second column with the parent medium's label for context - and I would like the column to be able to sort based on the label. However, if I use list_display to add field 'parent', that column sorts by the primary key. Demonstration: @admin.register(Medium) class MediumAdmin(admin.ModelAdmin): list_display = ('label', 'parent', 'parent_id') What's the correct or most elegant way of accomplishing this? I've seen suggestiongs to do it by adding a custom method to MediumAdmin that returns the parent label, and then apply the @admin.display(ordering='parent__label') decorator to it, but I feel like I'm missing a more correct way, since this is surely a common need.