Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Filter by latest() with reverse foreign key
I'm trying to make the following get_queryset more efficient, but I'm not sure how to get there. I need a list of Visits, each one being the first for a user. The following works, but is horribly inefficient: models.py: class User(models.Model): ... class Visit(models.Model): user = models.ForeignKey(User, related_name='visit_set') ... views.py class SomeListView(ListView): # Get a queryset of visits, each is a first() for a user. def get_queryset(self): users = User.objects.filter(visit_set__isnull=False) visit_ids = [u.visit_set.first().id for u in users] return Visit.objects.filter(id__in=visit_ids) How can I make this run without hitting the database for each user? -
Set current admin user as user to save in db under Django Admin TabularInline
I have a TabularInline under my admin page, and I want to prevent admins from editing submit_user field by making it read-only. However when creating a new entries in database, I need to be able to pass the current user as submit_user I've read many posts on stackoverflow but none of them works for me. Many suggested save_formset but it's simply not working for me. The db always complains about not having the submit_user field (if this case, the column has a ForeignKey that maps to another table User, and the complaint is about user_id. Thought have the user object should be fine, but it doesn't seem like it's the case.) my model looks like class SomeTable(model.Model): submit_user = models.ForeignKey(User, db_column='user') data1 = models.CharField(max_length=200) create_date = models.DateTimeField(null=False, default=datetime.datetime.now) -
Access a variable in HTML from a .py file
I want to have my HTML page access a variable from a .py file. My _version.py file is : version = "1.0.0" In my HTML page I want to read the above version from the _version.py and display as text. Is there a way to do this from html without making use of the render function and using the tags {{}}. I tried enclosing the python code within my html as follows, but it doesn't work: <li> Software version: <% from adapter_manager._version import __version__ %> <% print __version__ %> </li> -
Advanced serializing django models
I have these django models: class Event(models.Model): ts = models.CharField(max_length=25, editable=False) update_id = models.IntegerField( null=False) msg_id = models.CharField(max_length=50, primary_key=True, blank=True) chat = models.ForeignKey(Chat, on_delete=models.CASCADE, blank=True) user_id = models.ForeignKey(ChatUser, on_delete=models.CASCADE, blank=True) text = models.TextField(blank=True) is_visible = models.BooleanField(default=True, blank=True) edited_version = models.TextField(null=True, blank=True) and serializer: class UpdatesSerializer(serializers.ModelSerializer): class Meta: model = Event fields = ('ts', 'update_id', 'msg_id', 'chat', 'user_id', 'text') in views: def get(self, request): updates = Event.objects.all() updates = [UpdatesSerializer().to_representation(update) for update in updates] return Response(updates) it represents data like this: { "ts": 1, "update_id": 4, "msg_id": 1, "chat": 1, "user_id": 1, "text": "test" } How can I represent data like this? : { "ts": 1, "update_id": 4, "details":{ "msg_id": 1, "chat": 1, "user_id": 1, "text": "test" } } Actually I could separate this model and use fields from details as manytomany but it doesnt let me create event -
Django forgot password bootstrap customization
I'm currently in the process of trying to implement a forgot password functionality for my Django site which uses Bootstrap. I understand there is a way to use auth_views with the built-in forms that Django uses to quickly implement a reset password functionality, but I can't get my head around how to customize it enough so it fits on my template. I've created a custom form from where the user can fill in their email, but from there I don't understand how to pass the email to a django function/view which then uses the email to sends the password reset email (and then how to render the page where they can update their password with bootstrap as well?). I've had a look at the source html templates that ships with Django, but as a beginner of Django I don't understand how it's working. {% extends "admin/base_site.html" %} {% load i18n static %} {% block extrastyle %}{{ block.super }}<link rel="stylesheet" type="text/css" href="{% static "admin/css/forms.css" %}" />{% endblock %} {% block breadcrumbs %} <div class="breadcrumbs"> <a href="{% url 'admin:index' %}">{% trans 'Home' %}</a> &rsaquo; {% trans 'Password reset' %} </div> {% endblock %} {% block title %}{{ title }}{% endblock %} {% … -
How to update django auth User using a custom form
I am using Django's built in authentication to manage users on a social media website. I am using a one-to-one relationship to attach a profile to each user. I can update all the parts of the profile I have attached using an UpdateView. However I don't know how to do that with Django's built in User. So I created a form that uses the _meta class. I have gotten to the point where my form will add a new user instead of update the current one. I was hoping one of you could help me fix my code. Thanks in advance for any help you can offer views.py class PrivProfileUpdate(View): form_class = UserUpdateForm template_name = 'user/user_form.html' #display a blank form def get(self, request, pk): form = self.form_class(None) return render(request, self.template_name, {'form': form}) #proces form data def post(self, request, pk): form = self.form_class(request.POST) user = User.objects.get(pk=pk) if form.is_valid(): user = form.save(commit=True) print("we are trying to save") #cleaned (normalized) data username = form.cleaned_data['username'] password = form.cleaned_data['password'] first_name = form.cleaned_data['first_name'] last_name = form.cleaned_data['last_name'] email = form.cleaned_data['email'] user.set_password(password) #this is the only way to change a password because of hashing user.save() return render(request, self.template_name,{'form': form}) forms.py class UserUpdateForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) class Meta: model … -
Django - How to sort objects by an attribute of the first item in a sorted list of associated objects?
I want to achieve the following: I have one object, lets assume the following classes: class A(): title class B(): foreign key = A.id time #one-to-many relation I want to know what the view and template would look like if I wanted to display a list like: A.Title1 B.time #A is sorted on these ones B.time A.Title2 B.time #A is sorted on these ones B.time B.time Where each set of B() objects associated with one A() object are sorted by B.time, and the A() objects themselves are sorted by the top B.time in these A() objects. How would I achieve this? Thanks in advance! -
NoReverseMatch (django WRONG URL lookup)
New to Django. Using class based generic views to 'create' new songs and add them to the DB. There seems to be a wrong url lookup. Am greatful for the help. urls.py (look at the last URL - where the error occurs) from django.conf.urls import url import views app_name= 'music' # required for namespace urlpatterns= [ #/music/ url(r'^$', views.index, name='index'), #/music/register url(r'^register/$', views.UserFormView.as_view(), name='register'), # /music/71/ url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'), #/music/album/add/ url(r'album/add/$', views.AlbumCreate.as_view(), name='album-add'), #/music/album/2/ url(r'album/(?P<pk>[0-9]+)/$',views.AlbumUpdate.as_view(), name='album-update'), #/music/album/2/delete/ url(r'album/(?P<pk>[0-9]+)/delete/$',views.AlbumDelete.as_view(), name='album-delete'), #/music/login/ url(r'^login/$',views.LoginView.as_view(), name='login'), #/music/logout/ url(r'^logout/$',views.logout_user,name='logout'), #/music/songs/all/ url(r'^songs/(?P<filter_by>[a-zA_Z]+)/$', views.songs, name='songs'), #/music/71/add/ url(r'^(?P<pk>[0-9]+)/add/$', views.SongCreate.as_view(), name='song-add'), ] Attempt to go to the /music//add/ url to create a new song. Error shows no argument provided at 'detail' url. views.py class DetailView(LoginRequiredMixin, generic.DetailView): login_url= 'music:login' redirect_field_name= 'go_to' model= Album template_name= 'music/detail.html' class SongCreate(LoginRequiredMixin, CreateView): login_url='music:login' redirect_field_name='go_to' model=Song fields=['song_title','audio_file'] def form_valid(self, form): temp= form.save(commit=False) temp.album= self.request.album temp.save() return super(SongCreate, self).form_valid(form) The ERROR as displayed on going to URL : http://127.0.0.1:8000/music/17/add/ is Request Method: GET Request URL: http://127.0.0.1:8000/music/17/add/ Django Version: 1.11.12 Exception Type: NoReverseMatch Exception Value: Reverse for 'detail' with arguments '('',)' not found. 1 pattern(s) tried: [u'music/(?P<pk>[0-9]+)/$'] Exception Location: /usr/lib64/python2.7/site-packages/django/urls/resolvers.py in _reverse_with_prefix, line 497 Python Executable: /usr/bin/python Python Version: 2.7.15 The template in template/music from root project … -
How to use background-image css property with Django static files
I know similar questions have been answered but there are no clear answers for how to do this in a linked css file, all suggest doing directly in the html file itself I have a Jobs project, with the following structure to get to the images folder: Jobs/core/static/core/images/search.jpg How can I set an input element's background-image property to 'search.jpg' in a css file that is referenced with <link rel="stylesheet" href="{% static 'core/css/index.css' %}" /> ? I have seen similar questions asked and all of the answers suggest things such as setting it inline on the element itself, but how can this be done in a linked css file? -
Django: select_for_update() on Foreign Key Relation
I've used select_for_update() a lot. However, in all the cases I've used it, it has been through a manager like so: with transaction.atomic(): transaction = Transaction.objects.select_for_update().get(id="12345-6789-10") transaction.status = StatusEnum.APPROVED transaction.save() However, I sometimes get the transaction via a reference from another object. For example: transaction = another_object.transaction transaction.status=StatusEnum.APPROVED transaction.save() ^^ This will not lock the row. Instead, I would have to do this: transaction = Transaction.objects.select_for_update().get(id=another_object.transaction.id) My question: if another object has a foreign key relation to a Transaction, is there a way to lock the Transaction object without writing a get query? I understand performance-wise both options are about the same. Just looking for something a bit cleaner. Thanks! -
Django Queryset is not iterable
Right now i am trying to pull all of the objects out of my database and display them onto a web page using django and PostgreSQL, the syntax is slightly different due to the use of the Django Mako Plus framework, but the underlying code is the same. The only major difference is that in the template the syntax is changed from {{code here}} to ${code here}. Here is my view: from django.conf import settings from django_mako_plus import view_function from datetime import datetime from django.http import HttpResponse, HttpResponseRedirect from django import forms from homepage import models as cmod from django.contrib.auth import authenticate, login from django.shortcuts import render from homepage.models import User # from homepage.models import from homepage.models import DReferForm import random, string @view_function def process_request(request): dReferral = DReferForm.objects.all() context = { 'dReferral':dReferral, } # The DMP Equivalent when rendering the page return request.dmp.render('submissions.html', context) Here is my template: <%inherit file="base.htm" /> <%block name="content"> <h1>Testing</h1> %for i in dRefferal: <p>Doctor Name: ${i.Fname}</p> %endfor </%block> Whenever I try to load the webpage, I get an object not iterable error. If I use this exact same code on any other model it works just fine and pulls all the data. Thank you for … -
How to update a FloatField: Django
I'm trying to update field in my models with the newly calculated value from my view and when I try to update my field using total.objects.update(total=total) this is what i get 'decimal.Decimal' object has no attribute 'objects'. I also have some other questions, I'm currently calculating the total field from initial values inputted when the item is created, using the save() method. is this a good idea ? or is there a better way of doing this? the reason I'm currently doing this is because i display the a list of items with their initial values. Over all I'm trying to make a tools inventory system. I also have some other concerns. How can I use this view on multiple items types? the model items is an abstract model that contains all common fields,and every tool type inherits this model and will be using the same operations, calculate the new cantidad_existente and update the total fields. Is there a better way? my views.py def calcular_nueva_cantidad(ce, up): total = ce + up return total class updateForm(forms.Form): update = forms.IntegerField() def actualizar_cantidad(request, pk): # trae de la base de datos el valor de la cantidad existente cantidad_existente = Cortadores.objects.filter(pk=pk).values('cantidad_existente') c = cantidad_existente.values_list('cantidad_existente', … -
How to create a custom widget in Django Forms
In my Django template I have written html for a radio button section: <section class="section-units"> <fieldset id="filter-units" class="mod-choices radios mod-inline"> <label>Units:</label> <div class="form-group"> <input class="form-control" checked="checked" id="metric_0" name="metric" type="radio" value="LE"> <label for="metric_0">Length</label> </div> <div class="form-group"> <input class="form-control" id="metric_1" name="metric" type="radio" value="AV"> <label for="metric_1" data-toggle="tooltip" data-placement="bottom" title="Details on this meters">Average</label> </div> </fieldset> </section> I want to use the form widgets to render this html. This way the template will just call the custom widget like: <section class="section-units"> <fieldset id="filter-units" class="mod-choices radios mod-inline"> <label>Units:</label> {{ form.filter_units }} </fieldset> </section> But I'm not sure what to put in my forms.py class InputForm(forms.ModelForm): widgets = { 'filter_units': forms.RadioSelect( ), } -
How to delete PK and file in FileField django?
I have a modelform with a FileField, so I just add some files with some descriptions for my database. It adds a file in the location I have defined in MEDIA_ROOT and adds a PK for each item. For example consider that I add 5 objects with 5 files. My problem is that when I delete all 5 objects, from shell or admin, the corresponding files and PKs won't be deleted, And when I add another object, the PK starts from 6. How can I completely delete an object with its corresponding file and PK and sort the others, for example if I delete the 3rd object, I want that the 4th and 5th objects, became 3rd and 4th. -
Django and Jenkins multiple errors on execute shell
I am trying to implement continuous integration for a python-django app. I installed Jenkins on a vps and created a job which pulls my bitbucket code. Now I am trying to execute the tests from the tests dir, but something is failing within my execute shell in Jenkins. Here is the shell console output: 7 - Link the cms_core app in the project using a symbolic link /var/lib/jenkins/workspace/ed1cms/test_cms_core total 16 drwxr-xr-x 3 jenkins jenkins 4096 Jul 5 16:12 . drwxr-xr-x 5 jenkins jenkins 4096 Jul 5 16:12 .. lrwxrwxrwx 1 jenkins jenkins 16 Jul 5 16:12 cms_core -> ../core/cms_core -rwxr-xr-x 1 jenkins jenkins 811 Jul 5 16:12 manage.py drwxr-xr-x 2 jenkins jenkins 4096 Jul 5 16:12 test_cms_core /tmp/jenkins7283490794872735254.sh: line 28: prinf: command not found Collecting cms_core Could not find a version that satisfies the requirement cms_core (from versions: ) No matching distribution found for cms_core 8 - Finally, we can run the tests through django-jenkins Traceback (most recent call last): File "./manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/var/lib/jenkins/.virtualenvs/tmp-8ca50c09c788e0c/lib/python3.6/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/var/lib/jenkins/.virtualenvs/tmp-8ca50c09c788e0c/lib/python3.6/site-packages/django/core/management/__init__.py", line 307, in execute settings.INSTALLED_APPS File "/var/lib/jenkins/.virtualenvs/tmp-8ca50c09c788e0c/lib/python3.6/site-packages/django/conf/__init__.py", line 56, in __getattr__ self._setup(name) File "/var/lib/jenkins/.virtualenvs/tmp-8ca50c09c788e0c/lib/python3.6/site-packages/django/conf/__init__.py", line 41, in _setup self._wrapped = Settings(settings_module) File "/var/lib/jenkins/.virtualenvs/tmp-8ca50c09c788e0c/lib/python3.6/site-packages/django/conf/__init__.py", line … -
Is it more "Djangoistic" to use IDs or object names in a urlpattern?
Most languages and frameworks have an "-istic" way of doing things. For example, in Python there may be multiple ways of performing an operation but one way may be more Pythonistic than the others. When you're creating a Django urlpattern that represents a user acting on some object, is it more Djangoistic to use each object's id field or each object's name when creating the urlpattern? As an example, if 'user1' is "tagging" an object 'object1' (this object could be another user or some thing such as a car) and the user and the object each have both an id field and a name field (which may or may not contain spaces), which would be the more Djangoistic way to specify that URL? Use this? /tags/user1/object1 Or this? /tags/<user1_id>/<object1_id> If object1 has a long name containing spaces a you could wind up with a rather ugly URL: /tags/carjunkie/1972%20Ford%20Gran%20Torino (I should note that in my application, I wouldn't have any control the name of the car in this situation and could actually wind up with with the above URL). But there are also drawbacks to using each object's database id field. If the url looks like /tags/10/100 A competitor could surmise … -
How do I compare a dictionary value in django template
I have a dictionary object which is being passed to a Django template, say, d with structure {'sub':['sub1','sub2','sub3']}. If I display the value using key-value pair as {% for k,v in d.items %} <p>{{k}}:{{v.0}}</p> {% endfor %} it outputs sub:sub1, which is expected. But when I check if the first element of the value list is not empty {% for k,v in d.items %} {% if v.0 != "" %} <p>{{k}}:{{v.0}}</p> {% endif %} {% endfor %} it throws me an exception Could not parse the remainder: '% if v.0 != "" %' from '% if v.0 != "" %' -
django 3 tables queryset
I have 3 tables populated from my Postgresql legacy DB. I was able to get some data from vlan table but I have a trouble getting all the data from 3 different tables and put them into a table I created in the picture. I have tried multiple querysets such as list(chain(nameOfTables..)) Can you please help me? I have attached the image of the table Models.py from django.db import models class Gateways(models.Model): vip = models.GenericIPAddressField(primary_key=True) vlan = models.ForeignKey('Vlans', models.DO_NOTHING, blank=True, null=True) master = models.GenericIPAddressField(blank=True, null=True) backup = models.GenericIPAddressField(blank=True, null=True) nat = models.GenericIPAddressField(blank=True, null=True) vhid = models.IntegerField(unique=True, blank=True, null=True) class Meta: managed = True db_table = 'gateways' class Subnets(models.Model): subnet = models.TextField(primary_key=True) # This field type is a guess. vlan = models.ForeignKey('Vlans', models.DO_NOTHING, blank=True, null=True) dhcp = models.NullBooleanField() dhcp_start = models.GenericIPAddressField(blank=True, null=True) dhcp_end = models.GenericIPAddressField(blank=True, null=True) dns = models.GenericIPAddressField(blank=True, null=True) class Meta: managed = True db_table = 'subnets' class Vlans(models.Model): vlan_id = models.IntegerField(primary_key=True) allocated = models.NullBooleanField() name = models.TextField(blank=True, null=True) class Meta: managed = True db_table = 'vlans' Views.py def niro_list(request): gateways = Gateways.objects.all() vlans = Vlans.objects.all() subnets = Subnets.objects.all() context = { 'gateways': gateways, 'vlans': vlans, 'subnets': subnets, } return render(request, 'niro/niro_list.html', context) niro_list.html <div class="table-responsive-sm"> <table class="table"> <thead> <tr> … -
Django does not download file, just shows decode in server response
Been following these SO questions to get file downloads working in a Django/React app. Django download a file Download a file with Django Here is the code I have: def download(self, request, *args, **kwargs): data = UserToDocument.objects.filter(user_id=request.user.id, document_id=kwargs.get('doc_id')) if data: doc = Documents.objects.get(id=kwargs.get('doc_id')) file_path = settings.DOWNLOAD_ROOT + '/' + str(doc) if os.path.exists(file_path): with open(file_path, 'rb') as fh: response = HttpResponse(fh.read(), content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename=' + str(doc) return response return HttpResponse('success') return HttpResponse('document does not exist') First, it is checking if the current user is allowed to download the file. If they are, then it checks if the file exists on the server. It should then download the file if all of these requirements are met. This should prevent people from downloading documents they are not allowed to. All of these checks are working. If I remove authorization to a document for a user, they are unable to download it. Also, if I remove the file from the server, it won't try to download. That is to say everything is working up to with open(file_path, 'rb') as fh: Actually, it does try to download the file, but the server responds with the following and nothing downloads: The questions: 1) How … -
Django static file inclusion
Below is my folder structure for django project. The remaining files are working well. When I load the polls app in chrome then I get the message 'going to be affected'. As you can see I have also included a css file to the project and in that css file I am doing nothing but giving normal styling. p{ background-color:red; } But when I load the app in the browser it is not showing background color as red. In short there is no effect of the css file. What I am doing wrong -
Using callable as path attribute of Django's FilePathField?
I have the following model that includes a file upload by a user. def resume_path(instance, filename): # file will be uploaded to MEDIA_ROOT/user_<id>/resume/<filename> return 'user_{0}/resume/{1}'.format(instance.student_user.id, filename) class Resume(models.Model): resume = models.FileField(upload_to=resume_path, blank=True, null=True) pub_date = models.DateTimeField(default=timezone.now) student_user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) Then, I would like to allow a user to select one of their uploaded files in a later form. So, I need to be able to dynamically set the path to the directory containing that user's files similar to the dynamic way that I set the upload_path in the original model. I've tried the following according to this link: def resume_directory_path(instance): # returns the path: MEDIA_ROOT/user_<id>/resume/ return 'user_{0}/resume/'.format(instance.student_user.id) class JobApplication(models.Model): student_user = models.ForeignKey(StudentUser, on_delete = models.CASCADE) resume = models.FilePathField(resume_directory_path, null=True) However, looking at the documentation for FilePathField in Django 3.0, it doesn't look like it takes a callable for the path attribute. So, I'm not sure how the answer in the above link answers my question. What is the best way to achieve this functionality? -
How to use index values of a queryset in Django template
I'm trying to use index values of a queryset in Django template. In views.py, I passed json data into the template level, and I'm accessing the data with {{ data.index.image.sizes.Original.url }}. The index is what I manually made by {% with %} keyword like you see in the below codes. However, for some reason, the index seems not to be recognized as a number in {{ data.index.image.sizes.Original.url }}. I'm pretty sure there's nothing wrong on my codes because it worked well when I replace it with {{ data.0.image.sizes.Original.url }} which I just put an actual index number manually. How can I do that by using an index variable? {% for pic in store.photo_set.all %} {% with index=forloop.counter0 %} {% if pic.photo %} <img id="slider-img" class="img-responsive slider-img" src="{{ data.index.image.sizes.Original.url }}" alt="Product of {{ store.businessName }}"> {% endif %} {% endwith %} {% endfor %} -
single input django form
I'm trying to get a single input from django form but its giving me error ValueError at /books/f/ The view main.views.select_team didn't return an HttpResponse object. It returned None instead. view def select_team(request): if request.method == 'POST': Team.objects.create(user=request.user, total=request.POST('team_number')) return redirect(reverse('books', args=())) form <form action="{% url 'select_team' %}" method="post" style="display: inline;"> {% csrf_token %} <input type="number" id="start" name="'team_number'" min="2" max="5" value="2"/> <label for="start">select in range of 2 to 5</label> <button type="submit" class="btn btn-danger btn-xs"> <span class="glyphicon glyphicon-remove"></span>&nbsp; create teams </button> </form> url url(r'^books/f/$', views.select_team, name='select_team') -
Django forms: Is it possible to have multiple drop down menus for different tags within a field?
I have a form in a formset where I would like to display multiple drop down menus under a single field 'tests'. I have achieved this in the form of having a single dropdown menu within 'optgroup' tags (see image below). I guess this way you can only choose a single value. However, is it possible to 'nest' these drop downs? I.e have them all under one field 'tests', but be able to have several dropdowns with 'tags' and choose results for each tag? Or do I need a field for each 'tag'? My forms.py: class ReportForm(forms.ModelForm): summary = forms.CharField( widget=forms.Textarea(attrs={'rows':3, 'cols':70}), label='', required=False) tests = forms.CharField(widget=forms.HiddenInput()) class Meta: model = ClinicallyReportedSample fields = ('id', 'summary', 'tests', 'hilis_reported') def __init__(self, *args, **kwargs): json_data = kwargs.pop('json_data', None) super(ReportForm, self).__init__(*args, **kwargs) crs_obj = self.instance for j in json_data: if j['lab_no'] == str(crs_obj): json = j summary = json['summary'] self.fields['summary'].initial = summary self.fields['reported'].label = crs_obj tests = json.get('tests', None) if tests: test_choices = ( ('mutated', 'mutated'), ('mutated - see comments', 'mutated - see comments'), ('awaiting confirmation', 'awaiting confirmation'), ) self.fields['tests'] = forms.ChoiceField( required=True, label='Current or repeat samples?', choices=((k, test_choices) for k in tests), ) What I get now: I would instead want a … -
get all the existing fields from main class model
I have these django models: class Event(models.Model): ts = models.CharField(max_length=25, editable=False) update_id = models.IntegerField( null=False) class Message(Event): msg_id = models.CharField(max_length=50, primary_key=True) chat = models.ForeignKey(Chat, on_delete=models.CASCADE) user_id = models.ForeignKey(ChatUser, on_delete=models.CASCADE) text = models.TextField() is_visible = models.BooleanField(default=True) edited_version = models.TextField(null=True, blank=True) class AuthorsUpdate(Event): chat = models.ForeignKey(Chat, on_delete=models.CASCADE) user_id = models.ForeignKey(ChatUser, on_delete=models.CASCADE) action_id = models.CharField(max_length=50, null=False) Since Message and AuthorsUpdate are more like ManyToManyFields and independent, how can I serialize them when calling Event ( by Event.objects.all() )?