Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ModelMultipleChoiceField returns queryset instead of object instance
Hello I have this problem with multiple checkbox select I have this form class AnswerForm(forms.ModelForm): class Meta: model = Response fields = ('answer', ) def __init__(self, *args, **kwargs): question = kwargs.pop('question') super().__init__(*args, **kwargs) self.fields['answer'].queryset = question.answers.order_by('text') if question.question_field_type == 'multiple': self.fields['answer'] = forms.ModelMultipleChoiceField( widget=forms.CheckboxSelectMultiple( attrs={'autocomplete': 'off'}), queryset=question.answers.order_by('text'), ) My problem is that on submission it raises this error "<QuerySet [<Answer: A. High School Diploma>, <Answer: B. Associate's Degree>]>": "Response.answer" must be a "Answer" instance. how do make these to return answer instance instead of a queryset. -
how can I restructure my project into a microservice architecture?
I have this example data, where I want to communicate with my main project (Django) which it will host each microservice via HTTP, RPC, and other protocols, but my issue is that flask some endpoint are slow this can be improved later, but should I paginate the data on flask or Django? 2) if the data is already paginated how can I access all data from Django to the client(react any other stack)? note: the core service behind flask uses mongo(pymongo) + redis and bson. I did a benchmark using flask + tornado / Django + REST framework, where you can see there is no difference in timing . I want to build this platform as multiple services without caring if xyz component is done by xyz stack tech , and Django will be the front of all microservices by wrapping all data from all microservices together. should I add features like throttling, auth, tokens, pagination, and more from each service or handle from Django(front backend) ?? Execution Time: 0:00:06.451492 # flask Execution Time: 0:00:06.432626 # django { "count": 152983, "matches": [ { "Modified": "2020-11-11T22:15:00", "Published": "2020-11-11T22:15:00", "access": {}, "assigner": "cve@mitre.org", "cvss": null, "cwe": "CWE-601", "id": "CVE-2020-26219", "impact": {}, "last-modified": … -
How to show in Django Admin the list of Activities a user has made
I am trying to get the most out of my Django Blog project and wanted to know how to show in the admin the activities that a user has made like making comments or giving likes to posts. I need some hints and guidance on how to add this information in the admin.py Here is the models.py in Blog App class Post(models.Model): title = models.CharField(max_length=100, unique=True) content = RichTextUploadingField(null=True, blank=True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='author') date_posted = models.DateTimeField(default=timezone.now) slug = models.SlugField(blank=True, null=True, max_length=120) liked = models.ManyToManyField(User, default=None, blank=True, related_name='liked') def __str__(self): return self.title def get_absolute_url(self): return reverse('blog:post-detail', kwargs={'slug': self.slug}) def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.title) super(Post, self).save(*args, **kwargs) class Meta: verbose_name_plural = 'Blog Posts' class Comment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) content = models.TextField(max_length=300) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now=True) def __str__(self): return f"{self.post}-{self.user}-Comment No.{self.pk}" LIKE_CHOICES = ( ('Like', 'Like'), ('Unlike', 'Unlike') ) class Like(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) value = models.CharField(choices=LIKE_CHOICES, max_length=8) created = models.DateTimeField(auto_now=True) def __str__(self): return f"{self.post}-{self.user}-{self.value}" Here is the models.py in Users App class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') This is what I have tried in the models.py in Users app … -
django api how upload multiple images
I tried many times, but I just register the last one im my model class PropertyImage(models.Model): property = models.ForeignKey(Property, default=None, on_delete=models.CASCADE,) images = models.ImageField(upload_to=upload, null=True, blank=True) def __str__(self): return str(self.images) serializer class PropertyImageSerializers (serializers.ModelSerializer): class Meta: model = PropertyImage #fields =('name','') fields = '__all__' my class view handler the post request, I tried to user method FOR to loop all images and save view def post(self, request, *args, **kwargs): for images in request.FILES.getlist('images'): serializer = PropertyImageSerializers() serializer.property(request.data['property']) serializer.images(images) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) I get this error message: AttributeError: 'PropertyImageSerializers' object has no attribute 'property' but im my model you can see I have the property -
dateparser TypeError: expected string or bytes-like object
This is my Custom command and I want to convert a string from JASON like publication date: ['A week ago'] to a real date to create it in my Django database. but when I run the command I got this error. I don´t know if is for my command code or the JSON. this is my models: from django.db import models # Create your models here. class Job(models.Model): job_title = models.CharField(max_length=200) company = models.CharField(max_length=200) company_url = models.URLField(max_length=200) description = models.TextField() salary = models.CharField(max_length=200) city = models.CharField(max_length=200) district = models.CharField(max_length=200) publication_date = models.DateTimeField() job_url = models.CharField(max_length=200) job_type = models.CharField(max_length=200) def __str__(self): return self.job_title from django.core.management.base import BaseCommand from jobs.models import Job import json from datetime import datetime import dateparser class Command(BaseCommand): help = 'Set up the database' def handle(self, *args: str, **options: str): with open('static/data.json', 'r') as handle: big_json = json.loads(handle.read()) for item in big_json: #Convertir fecha publication_date = dateparser.parse('publication_date') existing_job = Job.objects.filter( job_title = item['job_title'], company = item['company'], company_url = item['company_url'], description = item['description'], publication_date = item['publication_date'], salary = item['salary'], city = item['city'], district = item['district'], job_url = item['job_url'], job_type = item['job_type'], ) if existing_job.exists() is False: Job.objects.create( job_title = item['job_title'], company = item['company'], company_url = item['company_url'], description = item['description'], … -
Django: How to change field name in nested serializer
Currently, I have this serializer: class TokenSerializer(serializers.ModelSerializer): """ Serializer for Token model """ user = UserDataSerializer(many=False, read_only=True) class Meta: model = TokenModel fields = ('key', 'user') And this is the response I get: { "key": "d1de7dd82f2b987a6d9f35f1d033876e164f7132", "user": { "username": "peter258", "first_name": "Peter", "last_name": "Jones", "email": "peter.jones@gmail.com" } } I would like to change the response so instead of saying "user" it says "data" but when I change the serializer to something like this, I only get the "key" in the response: class TokenSerializer(serializers.ModelSerializer): """ Serializer for Token model """ data = UserDataSerializer(many=False, read_only=True) class Meta: model = TokenModel fields = ('key', 'data') How do you properly change the name of the "user" field inside nested serializers? -
Multiple foreign key lookups
I have the following models in my app Account class Account(CommonModel): # Accounts received from Client client = models.ForeignKey('Client', on_delete=models.RESTRICT) reference = models.CharField(db_index=True, max_length=50) def __str__(self): return f"{self.client} {self.reference}" Person class Person(CommonModel): title = models.CharField(max_length=100,choices=choi.person_title()) name = models.CharField(db_index=True, max_length=100) birth_date = models.DateField() def __str__(self): return f"{self.title} {self.name}" AccountPerson class AccountPerson(CommonModel): # Account -> Person link account = models.ForeignKey("core.Account", on_delete=models.RESTRICT, related_name="accountperson_account") person = models.ForeignKey("core.Person", on_delete=models.RESTRICT, related_name="accountperson_person") contact_type = models.CharField(max_length=50, choices=choi.contact_type()) def __str__(self): return f"{self.account} - {self.person} ({self.contact_type})" The AccountPerson model holds relationships between accounts and people (one person can have multiple accounts). I'm trying to return a query set containing a list of Accounts, and the Person they're linked to (if any). My background is SQL, so I'm thinking of a query that would hit Account -> AccountPerson --> Person, but I'm stuck. I've tried prefetch_related() but I'm only returning details in the Account table - I'm unsure of how to access Person from there and put those fields into my HTML file. View def account_list(request): data = Account.objects.all().prefetch_related('accountperson_account') return render(request, 'core/account_list.html', {'data': data}) account_list.html Code condensed for readability ... {% for i in data %} <tr> <td>{{i.client}}</td> <td>{{i.reference}}</td> {% endfor %} ... I'm currently in a position where my page … -
Reverse for 'app_list' with keyword arguments '{'app_label': ''}' not found. 1 pattern(s) tried: ['admin/(?P<app_label>auth|landing)/$'] [closed]
https://dpaste.org/aNOQ - кто может помочь вот ошибка Reverse for 'app_list' with keyword arguments '{'app_label': ''}' not found. 1 pattern(s) tried: ['admin/(?P<app_label>auth|landing)/$'] Изменил change_form, кнопка добавилась но по пути моего приложения там где должны быть все модели выскакивает именно эта ошибка http://127.0.0.1:8000/admin/landing/ -
Django - Is there a way to validate a model with its related models before transaction commit?
Suppose I have two related models (my case is a bit more complicate, but the idea is same): class Main(models.Model): amount: int = models.IntegerField() class Child(models.Model): main: Main = models.ForeignKey(Main, on_delete=models.CASCADE) amount: int = models.IntegerField() Whenever creating or changing a Main instance, I want to make sure that it is 'valid'. In my case, a valid Main object means that the sum of all of its children amounts is equal to its own amount: def validate_main(main: Main) -> bool: children = Child.objects.filter(main=main) return sum(child.amount for child in children) == main.amount If I'm right, this creates a deadlock: I can't call validate_main before saving Main, because then I wouldn't be able to create and save the related Child instances (because Main won't have pk), so this check will fail. I can't call validate_main after saving Main, because this will enable a situation where there is an invalid state in the database (someone can create a Main without ever creating its children). I thought about validating the changes in the database just before every transaction commit, by this allowing to create both Main and its children in the same transaction.atomic context, but it seems Django doesn't have that kind of signal integration. -
Assertion failure on django project
I am new to python. I have created a Django project and I am running it locally. My python project keeps runs fine until I run a function from my main.py file. The function runs fine but then python crashes: Assertion failed: (NSViewIsCurrentlyBuildingLayerTreeForDisplay() != currentlyBuildingLayerTree), function NSViewSetCurrentlyBuildingLayerTreeForDisplay, file /AppleInternal/BuildRoot/Library/Caches/com.apple.xbs/Sources/AppKit/AppKit-1894.50.103/AppKit.subproj/NSView.m, line 13568. However I am unsure why this error is appearing. Anyone have experience in this type of error? -
Django: How to reduce size and increase cohesion of views
As my project is becoming bigger and bigger, I am starting to get very large CBVs because they are required to handle a lot of actions especially live responses through AJAX (More single page application style). For example I have class ScheduledBooking. It does everything from showing timelines of bookings, booking appointments and viewing/editing other appointments in one page. I utilise a variety of model managers for complex filtering/aggregation but not sure if it's Pythonic to extend it's role of these managers to handling booking actions such as allocating bookings, checking availability of bookings, broadcasting bookings (Even if they use other models)? To reduce size and cohesion of the view although the model manager then will just take on the workload affecting it's own level of cohesion. Or is there a better way/alternative for this? Another problem is the Live Responses from ajax. I use a large amount due to a single page application style although the action handling clogs up a lot of the view. I was wondering if there is an alternative place or way this can be handled? class ScheduledBooking(TemplateView, BetterFormsChoiceValidationMixin, SessionHandlerMixin, BookingMixin, AJAXFormSerialiserMixin): template_name = 'emissions_dashboard/booking_scheduled.html' def get_context_data(self): [... 20 lines..] return args def get(self, request, … -
How to add pagination to search view in django
could you please support adding pagination to the below search function based view, here is my code def post_search(request): form = SearchForm() query = None results = [] if 'query' in request.GET: form = SearchForm(request.GET) if form.is_valid(): query = form.cleaned_data['query'] search_vector = SearchVector('title', weight='A') + \ SearchVector('body', weight='B') search_query = SearchQuery(query) results = Post.published.annotate( search=search_vector, rank=SearchRank(search_vector, search_query) ).filter(rank__gte=0.1).order_by('-rank') return render(request, 'blog/post/search.html', {'form': form, 'query': query, 'results': results}) -
Custom login using Django's user template
I'm trying to make my custom login form using Django's user template. What i'm trying to do is the authentication of a user using username and password. Register works, every user is registered correctly, but when i'm trying to login using the correct fields, my: user = authenticate(request, username=username, password=password) returns None as value. Here is my def login_view in views.py (i'm using logger to know what is going on) def login_view(request): import logging logging.basicConfig(filename='mylog.log', level=logging.DEBUG) logging.debug('inizio') title = 'LOGIN' form = UserLoginForm() if request.user.is_authenticated: return redirect('board.html') if request.method == 'POST': form = UserLoginForm(request=request, data=request.POST) username= request.POST.get('username') password= request.POST.get('password') print(form.errors) if form.is_valid(): logging.debug('form is valid') logging.debug('called form.save(), result=%s', UserLoginForm) logging.debug('username, result=%s', username) logging.debug('password, result=%s', password) user = authenticate(request, username=username, password=password) logging.debug('user, result=%s', user) #### if user is not None: login(request, user) logging.debug('username, result=%s', username) logging.debug('password, result=%s', password) messages.info(request, "You are now logged in as {username}") return redirect('board.html') else: messages.error(request, "Invalid username or password.") logging.debug('primo else') return redirect('/') #### else: print(form.errors) logging.debug('errore form: , result=%s', form.errors) messages.error(request, "Invalid username or password.") logging.debug('secondo') username = request.POST.get('username') password = request.POST.get('password') messages.error(request, "Invalid username or password.") logging.debug('username, result=%s', username) logging.debug('password, result=%s', password) return redirect('/') return render(request=request, template_name="login.html", context={"form": form , "title":title}) And that's my … -
Build Succeeds Locally | Succeeds & Fails at CodeBuild AWS | Build Logs Shows App Up and Running | Status In Progress Forever
I have a django app that runs fine locally, when I attempt to send it to CodeBuild, the Build logs shows my app running in the console however the build never completes and the status is "in progress" This is taking from the build logs showing that my build has succeeded: But the Status shows in "in progress" however it never installs: -
How to get anything else that a string with ChoiceField in django forms?
I created a form with some ChoiceField inside. My probleme is that I always get a string even if the value of my ChoiceField is an integer or an array. In my view I try to handle the data of the form and get something like that : formTemplate = QcmForm(request.POST) if(formTemplate.is_valid()): rep1 = formTemplate.cleaned_data['Q1'] print("REPONSE", rep1) print("::", type(rep1)) And this is what I get REPONSE : [('L', 1)] :: <class 'str'> So Here is how I defined my form and a second try I did with TypeChoiceField which wasn't sucessful : Q1_TITLE = "intitule of question" Q2_CHOICES = ( ([("L", 1)], "some item"), ([("W", 0.5)], "other item") ) class QcmForm(forms.Form): Q1 = forms.ChoiceField(choices = Q1_CHOICES, label=Q1_TITLE, initial='', widget=forms.Select(), required=True) So if I choose "some item" I get in my print a string instead of a list or a tuple. Next Try : I changeed with TypeChoiceField class QcmForm(forms.Form): Q1 = forms.TypedChoiceField(coerce=list, choices = Q1_CHOICES, label=Q1_TITLE, initial='', widget=forms.Select(), required=True) And here the result is worst, it consider my reponse as a list of character instead of a list of tuple. REPONSE : ['[', '(', "'", 'L', "'", ',', ' ', '1', ')', ']'] :: <class 'list'> Thank you for reading … -
Django encrypt FileField before saving it
I'm trying to save pdfs in the disk with django which is easy. However I want to encrypt them before saving them. As far as i know i should rewrite the save of the model to encrypt the file content before making the super().save() The problem is that i'm not managing to encryopt the content, i've tried with: self.file.write(f.encrypt(self.file.read())) However it does not modify anything. I'm not seeing with the debuger where the content of the file is to modify it or how should i do it. Thanks! -
Django : how to fix empty slug?
I have a urls : urlpatterns = [ url(r"admin/" , admin.site.urls), url(r"users/" , include(("users.urls", "users") , namespace='users') ), path('bristol/' , include(('bristol.urls', "bristol") , namespace='bristol') ), url(r"" , include('django.contrib.auth.urls')), ] But I can't connect to my server if I don't put any end slug to my url : What should I change in my url patterns to redirect localhost:8000 directly to the login view ? I tried : urlpatterns += [ url(r"/" , reverse("login"))] But It didn't help :-/ -
Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/accounts/signup in DJANGO even though urls is mapped correctly
Below is the urls.py file of sub-app accounts from django.urls import path from . import views urlpatterns = [ path("signup",views.signup,name='signup') ] This views.py of accounts def signup(request): if request.method == 'POST': firstname = request.POST['first_name'] lastname = request.POST['last_name'] username = request.POST['username'] password1 = request.POST['password1'] password2 = request.POST['password2'] email = request.POST['email'] if password1==password2: user = User.objects.create_user(firstname =first_name ,lastname =last_name ,username =username , email=email, password=password1) user.save(); print("USER CREATED SUCCESSFULLY") return redirect('login.html') else: return redirect('signup.html') I have even mapped the url in main url.py also, but still it is showing error. below is the signup.html The signup.html file <form action="signup" method="POST"> {% csrf_token %} <input type="text" name="first_name" placeholder="FIRST NAME"><br> <input type="text" name="last_name" placeholder="LAST NAME"><br> <input type="text" name="username" placeholder="USERNAME"><br> <input type="email" name="email" placeholder="EMAILID"><br> <input type="password" name="password1" placeholder="PASSWORD"><br> <input type="password" name="password2" placeholder="CONFIRM PASSWORD"><br> <input type="submit"> can anyone please help me out with this problem, i am not getting what went wrong. It is displaying page not found error. -
Is there way to call a Javascript function when a Django Admin Popup (Add, Update, Delete) completes?
Image, I have this situation, where I have bind the change event on Person field. We rely on some JavaScript to be run each time a select value changes. It is currently listening to the change event of said element, which works fine when the user clicks a value directly in the menu proposed by the select. Sadly, when this select is populated through the Admin Popup functionality, it seems the change event is not fired for the select, as our callback is not executed, even though the element's value is actually changed. Is there another event we can listen to to get the same behaviour than when the user clicks a value directly from the list ? -
Problem with Django not finding a module 'learning_logs'
I've been trying to fix this Django issue. I've just started this project and I'm fairly new to this language so I don't know where exactly is the issue. Error: Traceback (most recent call last): File "C:\Users\user\Desktop\Projects Python\Django\manage.py", line 22, in <module> main() File "C:\Users\user\Desktop\Projects Python\Django\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 377, in execute django.setup() File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\django\apps\config.py", line 90, in create module = import_module(entry) File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked ModuleNotFoundError: No module named 'learning_logs' models.py: from django.db import models # Create your models here. class Topic(models.Model): text = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return self.text settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'learning_logs', ] Any help I would really appreciate it. -
Display Django Templates after sucessfuly posting data
I got a problem with my Django templates: forms.py: class SupportForm(forms.Form): name = forms.CharField() message = forms.CharField() models.py: class Message(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) name = models.CharField(max_length=100) message = models.CharField(max_length=100) def __str__(self): return self.user.username views.py: class my_view(LoginRequiredMixin, View): def get(self, request, *args, **kwargs): try: messages = Message.objects.filter(user=request.user) context = { 'object': messages, } return render(self.request, 'my.html', context) except: return render(request, "my.html",{}) def post(self, request, *args, **kwargs): form = SupportForm(request.POST) if form.is_valid(): name = form.cleaned_data['name'] message = form.cleaned_data['message'] message_model = Message( user=request.user, name = name, message = message, ) message_model.save() return redirect('/my/') my.html: object:{{ objects }}<br> name:{{objects.name.1}}<br> message:{{objects.message.1}}<br> {% for item in objects_list %} {{ item.name }} {% endfor %} I want to post name and message in html and then show it under input. POST works fine. Then i want to display my name and message. The problem is with viewing my objects in html: i can't see anything. What am i doing wrong? -
Sending Serializer data by Request library in Django return (too many values to unpack (expected 2))
I am trying to send a data by Webhook, using Request Library in Django. whatever=Whatever.objects.filter(visibility=True) datas = WhateverSerializer(whatever,many=True).data webhooks = Webhooks.objects.filter(user=request.user,types="webhooks") headers = {'Content-Type': 'application/json;charset=UTF-8'} for wh in webhooks: r = requests.get(wh.data, headers=headers, data=datas) But I have a error 500: too many values to unpack (expected 2) What is the correct way to send it by webhook? -
how to hide html tags in head meta description when i use WYSIWYG - django
i want add meta description in tag for each post from my model so i add this line in head tag in html page <head> <!-- Facebook Meta Tags --> <meta property="og:description" content="{{android_posts.app_contect}}" /> </head> so i tried do that but the problem is when i see my page source it show html tags , also i tried add |safe in meta but nothing changed , any ideas please i'm using django -
Getting the number of comments from a specific post in django
I have a little problem with a query. I work on a blog website with django. For posts I have the first page where i display all the posts as a list, with their details (title, date posted etc.) and I want to display the number of comments for each post along with title, date posted and tags. I'm not sure how to make that, I need to implement something on the model classes or in view function that renders the page ? Here are the model classes. class Post(models.Model): author = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=500) content = models.TextField() tags = models.CharField(max_length=100) date_posted = models.DateTimeField(default=timezone.now) def __str__(self): return self.title class Comment(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) comment_text = models.TextField() date_posted = models.DateTimeField(default=timezone.now) def __str__(self): return f'{self.user.username} Comment ' + str(self.id) and the view function def blog(request): context = { 'posts': Post.objects.all(), 'title': 'Blog', 'banner_page_title': 'Blog', 'page_location': 'Home / Blog' } return render(request, 'blog/blog.html', context) -
Django REST API - SerializerMethodField() causes too many queries
I am a bit lost here. I have created a nested relationship that goes as follows: Text -> multiple Sentences-> multiple Words models.py: class Text(models.Model): title = models.CharField(max_length=250) class Sentence(models.Model): text = models.ForeignKey(Text, related_name='sentences', on_delete=models.CASCADE, blank=True, null=True) order = models.IntegerField() class Meta: unique_together = ['text', 'order'] ordering = ['order'] class Word(models.Model): sentence = models.ForeignKey(Sentence, related_name='words', on_delete=models.CASCADE, blank=True, null=True) order = models.IntegerField() word = models.CharField(max_length=50) vocabulary = models.ForeignKey(Vocabulary, on_delete=models.SET_NULL, blank=True, null=True) class Meta: unique_together = ['sentence', 'order'] ordering = ['order'] class Vocabulary(models.Model): vocabulary = models.CharField(max_length=50) class KnownWords(models.Model): vocabulary = models.ForeignKey(Vocabulary, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) The idea is that a text is split into individual words. Each word is associated with a vocabulary and users can know the vocabulary. serializer.py: class WordSerializer(serializers.ModelSerializer): is_known = serializers.SerializerMethodField() class Meta: model = Word fields = ['id', 'order', 'word', 'vocabulary', 'is_known '] def get_is_known(self, obj): if KnownWords.objects.filter(vocabulary=obj.vocabulary).exists(): obj.is_known = True else: obj.is_known = False return obj.is_known class SentenceSerializer(serializers.ModelSerializer): words = WordSerializer(many=True) class Meta: model = Sentence fields = ['id', 'order', 'words'] class TextSerializer(serializers.ModelSerializer): sentences = SentenceSerializer(many=True) vocabulary = serializers.SerializerMethodField() class Meta: model = Text fields = ['id', 'title', 'sentences'] views.py: class TextDetail(generics.RetrieveAPIView): queryset = Text.objects.prefetch_related('sentences', 'sentences__words') serializer_class = TextSerializer The reason why ìs_known is a …