Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Requests-oauthlib access token reuse in Django App
I'm able to fetch an OAuth2 access token using Backend Application Flow for Requests-Oauthlib. The API documentation states "Re-use the access token until it expires. Then, get a new token". from oauthlib.oauth2 import BackendApplicationClient client = BackendApplicationClient(client_id=client_id) oauth = OAuth2Session(client=client) token = oauth.fetch_token(token_url='https://provider.com/oauth2/token', client_id=client_id, client_secret=client_secret) The Requests-Oauthlib documentation states that you can save the token, but has no further information on how to do this. The token has 'expires_in' and expires_at fields returned in addition to the access token. I'm going to this in a Django App, but I'm not sure where to store the access token as it's for the Application, not User. How can I retain the token to re-use until it expires? -
Django - Cannot combine a unique query with a non-unique query or pub_date field look up not available
Trying to filter queries by name & datetime. The query should fulfill both criteria, i tried using field lookup in single query using pub_date__date field lookup , it threw the error pub_date not available, then i tried using date field, but that didnt work either. dtt here is = datetime.datetime.now() orders = OrderItemss.objects.filter(customer=customer_object, pub_date__date= str(dtt.day)) orders = OrderItemss.objects.filter(customer=customer_object, date= str(dtt.date()) when i tried combining 2 queries using & , it throws the error 'Cannot combine a unique query with a non-unique query' code: orders = OrderItemss.objects.filter(customer=customer_object) & Customer.objects.datetimes('date', 'hour', order='DESC') -
Custom User Model in Django throws SettingsReference error when making migrations
thanks in advance. I'm trying to build a custom user model and profile model for use in a Django app. I'm just subclassing the built-in CustomUser in case I want to add authentication features in the future, and adding all of the non-authentication related user information in CustomUserProfile. Here's the code: from django.db import models from django.conf import settings from django.contrib.auth.models import AbstractUser from django.utils.translation import ugettext_lazy as _ from django.db.models.signals import post_save class CustomUser(AbstractUser): # ADD AUTH FUNCTIONALITY IN THE FUTURE HERE pass def __str__(self): return self.email class CustomUserProfile(models.Model): # relates profile to user user = models.OneToOneField(CustomUser, related_name="profile", on_delete=models.CASCADE) # the next date the payment is due payment_due_date = models.DateField(null=True) def save(self, *args, **kwargs): # custom save logic will go here super().save(*args, **kwargs) def __str__(self): return f"Profile of user: {self.user.email}" # post save hook that creates a user profile for new users def create_user_profile(sender, instance, created, **kwargs): if created: CustomUserProfile.objects.create(user=instance) post_save.connect(create_user_profile, sender=BaseUser) And in the settings.py file, I have included the user model and profile with: AUTH_USER_MODEL = 'accounts.CustomUser' AUTH_PROFILE_MODULE = 'accounts.CustomUserProfile' The error I'm getting occurs when I run manage.py makemigrations. Specifically, it's returning AttributeError: 'SettingsReference' object has no attribute '_meta'. Frankly I'm not sure where to begin … -
REDIRECT_FIELD_NAME from django.contrib.auth
In my class-based django view, I am using redirect_field_name = REDIRECT_FIELD_NAME. May I know where I am redirecting to, and also by default, what is the field name and how I can set it? Thank you def zulip_login_required( function: Optional[ViewFuncT]=None, redirect_field_name: str=REDIRECT_FIELD_NAME, login_url: str=settings.HOME_NOT_LOGGED_IN, ) -> Union[Callable[[ViewFuncT], ViewFuncT], ViewFuncT]: actual_decorator = lambda function: user_passes_test( logged_in_and_active, login_url=login_url, redirect_field_name=redirect_field_name, )( zulip_otp_required( redirect_field_name=redirect_field_name, login_url=login_url, )(add_logging_data(function)) ) if function: return actual_decorator(function) return actual_decorator # nocoverage # We don't use this without a function -
How to customise the representation of fields of a nested serializer?
I am having a nested serializer as:- serializers:- class DeviceConfigSerializer(serializers.ModelSerializer): config = serializers.JSONField() context = serializers.JSONField() class Meta: model = Config fields = ['backend', 'status', 'templates', 'context', 'config'] class DeviceDetailSerializer(serializers.ModelSerializer): config = DeviceConfigSerializer() class Meta(BaseMeta): model = Device fields = [ 'id', 'name', 'organization', 'mac_address', 'key', 'last_ip', 'management_ip', 'model', 'os', 'system', 'notes', 'config', ] def update(): ... ... ... Views:- class DeviceDetailView(RetrieveUpdateDestroyAPIView): serializer_class = DeviceDetailSerializer queryset = Device.objects.all() When I try to get the data with a get request, this is what I receive:- but the fields in the HTML Form section of browsable API doesn't represent the context and config field in JSON format, instead, this is what I receive:- What I expect is to have the same representation of the context and config fields for the HTML Form and the JSON response. -
How to set session key in djago channels
I have a chat app and i want to use session key to save chats in models for persistence,how can i do this import json from channels.generic.websocket import AsyncWebsocketConsumer class ChatRoomConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name # Join room group await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() ........ -
Need to apply a clear function or rest for the following code to rest the input field
I need to apply a clear function when I add the input frequency. Now when I add a number say 2, 2 fields are created and when I add 3, it's getting appended and showing 5 fields. I need the exact number of fields as given in the input. Please give any tips <div class="container"> <div class="row"> <div class="col-4"></div> <div class="col-4"> <form method="post" enctype="multipart/form-data" autocomplete="off"> {%csrf_token%} <div class="mb-3"> <label>{{medicineform.frequency.label}}</label> </div> <div class="mb-3"> {{medicineform.frequency}} </div> <br> <div id="dynamicCheck"> <input type="button" value="+" onclick="createNewElement();"/> </div> <br> <div id="newElementId">Your time here</div> <br> <div class="mb-3"> <button type="submit" class="btn btn-block btn-primary">Add a reminder</button> </div> </form> </div> <div class="col-4"></div> </div> </div> </div> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <script> $(function () { $("#medicine").autocomplete({ source: '{% url 'autocomplete' %}', minLength: 2 }); }); </script> <script type="text/JavaScript"> function createNewElement() { var inpObj = document.getElementById("id_frequency").value; // First create a DIV element. var i; for (i=1;i<=inpObj;i++) { var txtNewInputBox = document.createElement('div'); // Then add the content (a new input box) of the element txtNewInputBox.innerHTML = "<input type='time' name='reminder' id='newInputBox'>"; // Finally put it where it is supposed to appear. document.getElementById("newElementId").appendChild(txtNewInputBox); } } </script> {% endblock %} -
How speed up sending email in Django rest framework?
I have a backend server that allows users to track the price of products on an ecommerce site. Whenever the price drops down, I'll have to send an informing email to my users. I have been written an API that updates the price of products and at the same time, sending an email if the price has dropped. So, the are thousands of emails have to be sent in one API call. Currently, I'm using django.core.email to sending email to users but it takes so long each time sending an email (about 3s-4s for each. If it has 5 product's prices dropped, the time of the API call will be around 20s). Is there any way to make a lot of emails sent within the shortest amount of time in my case? -
Image url not displaying my uploaded images when django project loaded onto heroku site
My uploaded images are not loading when uploaded to heroku and I think its not related to static file issue. When i set debug = False they come fine and i know that when it is false django uses itself to host the static assests. So setting that and my images loads fine but that's not the case if i set Debug = True on heroku or on my local env. Can somebody help me solve this issue. template <img class="img-fluid" style="height:auto;" src="{{post.work_img.url}}" alt="Generic placeholder image"> model class WorkExp(models.Model): work_img = models.ImageField(upload_to="work_images/") app/urls.py urlpatterns = [ path("carrer/", WorkExpView, name="carrer_page"), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) project/urls.py urlpatterns = [ path("admin/", admin.site.urls), path("", include("blog.urls", namespace="blog")), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
Django Excel Custom Column and Rows format
I want to customized Columns and Rows in Excel output like the image below. It is possible to make the same output in django using openpyxl workbook? This is my regular export excel code: def summary_excel(request): car_queryset = Reg_Date.objects.all() response = HttpResponse( content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', ) response['Content-Disposition'] = 'attachment; filename=Reg.xlsx' workbook = Workbook() worksheet = workbook.active worksheet.title = 'Reg' columns = [ 'SUBJECT:', 'PERSONEL:', 'LOGOUT:' ............. ] row_num = 1 for col_num, column_title in enumerate(columns, 1): cell = worksheet.cell(row=row_num, column=col_num) cell.value = column_title for car in car_queryset: row_num += 1 row = [ car.subject, car.personel, car.time .................... ] for col_num, cell_value in enumerate(row, 1): cell = worksheet.cell(row=row_num, column=col_num) cell.value = cell_value workbook.save(response) return response -
To Fetch Data from scanned barcode number
I am new to Django,I am currently working on application that need barcode reading and fetch data from server.I am now able to get barcode from a scanned barcode. My question is: how can I get more information about a product from its barcode number in django (e.g. product price)? Can I do this from the barcode_scan library, or will I need something else? -
Django functional index migration (postgres), error: invalid input syntax for type integer: "none"
I'm trying to create a functional index based on a newly created field in Django 3.2 (see the prerelease notes for more info about functional indexing), but keep getting the following error when migrations are run (using postgres): psycopg2.errors.InvalidTextRepresentation: invalid input syntax for type integer: "none" This seems like it may be a bug in the Django prerelease, but I'm not sure. I'm not just dumping all my code in this post; the larger block of code below is actually an auto-generated migration by django. The first code block is my code, where I just include the relevant fields and the problematic functional index. This code creates a new field "registration_volume" and a functional index "raw_demand" which should equal registration_volume/capacity if [capacity is not null and capacity>0], capacity being another field of the model), in a model called "Section": capacity = models.IntegerField( default=0, help_text="The number of allowed registrations for this section, " "e.g. 220 for CIS-120-001 (2020A).", ) registration_volume = models.PositiveIntegerField( default=0, help_text="The number of active PCA registrations watching this section." ) class Meta: indexes = [ Index( Case( When( Q(capacity__isnull=False) & Q(capacity__gt=0), then=( Cast("registration_volume", models.DecimalField()) / Cast("capacity", models.DecimalField()) ), ), default=None, output_field=models.DecimalField(null=True, blank=True), ), name="raw_demand", ), ] The auto-generated … -
Get django-filters working on 2 level foreign key relations
I have 3 models a-->b-->c. I want to add django-filter on c so that it could filter using the attributes/values of a. I have tried using ModelChoiceFilter, but only got it working till model b. Is there any way we could filter through 2 levels of foreign key relations? -
2 Options for permission_required in Django View
I have to render a page that requires either of the 2 permissions. views.py class Dashboard(TemplateView, PermissionRequiredMixin): permission_required = "m.view_dashboard" // I want to add another option like "m.add_item" template_name = "dashboard.html" so permission is either of the two options, view and add. Is there any way I can implement this through permission_required? -
Django: AUTH_USER_MODEL refers to model '%s' that has not been installed
I am trying to deploy a Django app to Heroku. It works on my localhost but I get this error when deploying to heroku: File "./blog/models.py", line 6, in <module> 2021-03-24T23:31:05.696194+00:00 app[web.1]: User = get_user_model() 2021-03-24T23:31:05.696219+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/auth/__init__.py", line 162, in get_user_model 2021-03-24T23:31:05.696372+00:00 app[web.1]: "AUTH_USER_MODEL refers to model '%s' that has not been installed" % settings.AUTH_USER_MODEL 2021-03-24T23:31:05.696397+00:00 app[web.1]: django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'auth.User' that has not been installed I have tried setting AUTH_USER_MODEL = 'auth.User' in settings after doing from django.contrib.auth.models import User and: from django.contrib.auth import get_user_model User = get_user_model() but nothing works. settings.py import django from django.core.wsgi import get_wsgi_application from django.core.asgi import get_asgi_application # from django.contrib.auth.models import User #todo: this causes ImproperlyConfigured: SECRET_KEY MUST NOT BE EMPTY import os import django_heroku DJANGO_SETTINGS_MODULE = 'django_project.settings' SECRET_KEY = 'asdaf123$9pv98=e6p^gl(-eoj' #todo: test removing this in own deployment DEBUG = 'True' ALLOWED_HOSTS = ['*', 'localhost', '127.0.0.1'] INSTALLED_APPS = [ 'django.contrib.auth', 'blog.apps.BlogConfig', #allows Django to correctly search your templates for the 'blog' app 'users.apps.UsersConfig', 'chat', 'crispy_forms', 'channels', 'dal', 'dal_select2', 'django.contrib.admin', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'storages' ] # ~~~MESSAGES CONFIG~~~ WSGI_APPLICATION = 'django_project.wsgi.application' ASGI_APPLICATION = 'django_project.asgi.application' # older version of django: 'django_project.routing.application' # Channels redis config: CHANNEL_LAYERS = { 'default': { 'BACKEND': … -
Getting an error while using HyperlinkedModelSerializer in DRF
When i run the URL http://127.0.0.1:8000/api/leave/, I get this frustrating error: Could not resolve URL for hyperlinked relationship using view name "leaveapplication-detail". You may have failed to include the related model in your API, or incorrectly configured the lookup_field attribute on this field. I found some solutions over the internet but none of them worked for me. What is the best way to solve this error? Currently i got this if i use ModelSerializer but i want to generate URL instead of id { "id": 7, "date_start": "2021-03-20", "date_end": null, "time_start": "09:00:00", "time_end": "13:00:00", "remarks": "something", "status": null, "type": 1, "leave_type": "Test" }, I have a models directory rather than models.py file. Here is the directory: models/ ......__init __.py ...... leaveApplication.py Here is my model: from leave.models.leavetype import LeaveType from django.db import models from authentication.models import TimeStampedModel, User class LeaveApplication(TimeStampedModel): date_start = models.DateField(default=None) date_end = models.DateField(default=None, null=True) time_start = models.TimeField(auto_now=False, auto_now_add=False, null=True) time_end = models.TimeField(auto_now=False, auto_now_add=False, null=True) remarks = models.TextField(default=None, null=True) status = models.CharField(max_length=255, null=True) type = models.ForeignKey(LeaveType, related_name='leave_applications',default = None, on_delete=models.CASCADE) user = models.ForeignKey(User, related_name='leave_applications',default = None, on_delete=models.CASCADE) Here is my Serializer: class LeaveApplicationSerializer(serializers.HyperlinkedModelSerializer): date_start = serializers.DateField(required=True) date_end = serializers.DateField(default=None, required=False, allow_null = True) time_start = serializers.TimeField( required=False, allow_null … -
Is it safe to render python dictionary data in html template in django or shall I use json?
When I learned about JSON data I am confused. I am rendering data in html template. data = {'user': username, 'data': data} return render(request, 'index.html', data) Is this way safe to use or I need to send response as JSON? Can you also explain how can I use JSON data in html template? How can I use jhinja format like python with JSON {{json data here}}? -
TypeError at /api/updateproducts/59 unhashable type: 'collections.OrderedDict' in Django Rest Framework
I created update-product API where I have to update many to many fields. Product models have m2m relationships with the Category and Variants model. I am able to update Category model fields using instance.category.set(), but when I try the same thing with Variants, it generates the above error. I am sending the raw JSON data like this. My models: class Category(models.Model): name = models.CharField(max_length=100, unique=True) image = models.ImageField(null=True, blank=True) class Meta: verbose_name_plural = "Categories" class Variants(models.Model): product_id = models.CharField(max_length=70, default='OAXWRTZ_12C',blank=True) price = models.DecimalField(decimal_places=2, max_digits=20,default=500) size = models.CharField(max_length=50, choices=SIZE, default='not applicable',blank=True,null=True) color = models.CharField(max_length=70, default="not applicable",blank=True,null=True) variant_image = models.ImageField(upload_to="products/images", blank=True) quantity = models.IntegerField(default=10,blank=True,null=True) # available quantity of given product variant_availability = models.CharField(max_length=70, choices=AVAILABILITY, default='available') class Product(models.Model): merchant = models.ForeignKey(Seller,on_delete=models.CASCADE,blank=True,null=True) category = models.ManyToManyField(Category, blank=False) brand = models.ForeignKey(Brand, on_delete=models.CASCADE) collection = models.ForeignKey(Collection, on_delete=models.CASCADE) variants = models.ManyToManyField(Variants,related_name='products') My views: class ProductUpdateView(UpdateAPIView): permission_classes = [AllowAny] queryset = Product.objects.all() serializer_class = ProductUpdateSerializer My serializers: class ProductUpdateSerializer(serializers.ModelSerializer): variants = VariantSerializer(many=True) class Meta: model = Product fields = ['id','category','featured', 'top_rated','brand','collection', 'name','description', 'main_product_image','best_seller', 'rating','availability','warranty','services','variants'] def update(self, instance, validated_data): instance.featured = validated_data.get('featured',instance.featured) instance.top_rated = validated_data.get('top_rated', instance.top_rated) instance.brand = validated_data.get('brand', instance.brand) instance.collection = validated_data.get('collection',instance.collection) instance.name = validated_data.get('name', instance.name) instance.description = validated_data.get('description', instance.description) instance.save() #category_logic category_data = validated_data.pop('category') instance.category.set(category_data) instance.save() #variants_logic variants_data … -
How to use array fields in Django models?
I have a model class Client and it has different fields. As shown below: class Client(models.Model): name = models.CharField(max_length = 100) dob = models.SlugField(max_length = 100) CNIC = models.SlugField(max_length = 100) property_type = models.CharField(max_length = 100) down_payment = models.IntegerField() date_posted = models.DateTimeField(default=timezone.now) installment_month = models.CharField(max_length = 100) installment_amount = models.IntegerField(null = True) installment_date = models.SlugField(max_length = 100) I have different templates and views for first 6 fields (as these will be asked when adding a new client to the database),and the last 3 fields(installment_month, installment_amount, installment_date) because these fields will be used everytime when client pays an installment. Now, when I try to add a new installment it asks me for these 3 fields but it replaces the values entered last time, because each of these 3 fields can only store 1 value. Does anyone has an idea how can I declare array fields for these so that they can store all the installments, their months and their date? -
django url not matching right url with reverse match error
I'm getting very unusual error in my django project because django reads the wrong url not stated in the href tag being clicked,the page to be navigated to is just a page with a simple url pattern while the page it's navigating to requires two arguments for reverse matching,since the page to be navigated to is just a simple url and doesn't provide the necessary parameters in the views and url path,it gives a no reverse match error saying it tried to match the reverse url pattern which in actuality is in another page. this what i'm trying to say: error: Reverse for 'search-friend-detail' with arguments '('', '')' not found. 1 pattern(s) tried: ['chat/search\-friend\-detail/(?P[^/]+)/(?P[^/]+)/$'] urls.py: urlpatterns = [ path('admin/', admin.site.urls), path('', include('users.urls')), path('posts/home.html', p_views.PostsListView.as_view(), name='posts-home'), path('friends/search.html', f_views.search, name='friends-search'), path('friends/add-friend/', f_views.SearchDetail, name='friends-search-detail'), path('friends/accept-requests/', f_views.AcceptRequests, name='accept-requests'), path('friends/accept-requests-detail/', f_views.AcceptRequestsDetail, name='accept-requests-detail'), path('chat/chatt.html', pc_views.SearchChat, name='chat-search'), path('chat/search-friend-detail/<str:username>/<str:usernamee>/', pc_views.SearchChatDetail, name='search-friend-detail'), ] the "chat-search" is the actual url i wish to navigate to in base.html file through this link: <a href="{% url 'chat-search' %}"><i class="fa fa-envelope"></i></a> but instead miraculously navigating to the last url i.e 'search-friend-search'. although the link is in my chatt.html file at: <a class="mr-2" href="{% url 'search-friend-detail' results.Accepter.username results.Added.username %}">{{ results.Added.username }}</a> my views.py: def … -
Issue deploying Django/websocket/redis project to heroku
I have a Django project, which is running fine on my machine, that uses redis and a couple of workers to utilize websockets and give constantly updated subway times. It works fine on my machine, but I'm logging errors like such on Heroku when I have it deployed: 2021-03-25T04:23:19.462596+00:00 app[worker2.1]: [2021-03-25 04:23:19,462: ERROR/MainProcess] beat: Connection error: Error 111 connecting to localhost:6379. Connection refused.. Trying again in 32.0 seconds... 2021-03-25T04:23:51.493083+00:00 app[worker2.1]: [2021-03-25 04:23:51,492: ERROR/MainProcess] beat: Connection error: Error 111 connecting to localhost:6379. Connection refused.. Trying again in 32.0 seconds... 2021-03-25T04:22:11.000000+00:00 app[heroku-redis]: source=REDIS addon=redis-concentric-76659 sample#active-connections=1 sample#load-avg-1m=0.23 sample#load-avg-5m=0.51 sample#load-avg-15m=0.42 sample#read-iops=0 sample#write-iops=0.061111 sample#memory-total=15629040kB sample#memory-free=7601200kB sample#memory-cached=3699616kB sample#memory-redis=326704bytes sample#hit-rate=1 sample#evicted-keys=0 2021-03-25T04:24:23.524980+00:00 app[worker2.1]: [2021-03-25 04:24:23,524: ERROR/MainProcess] beat: Connection error: Error 111 connecting to localhost:6379. Connection refused.. Trying again in 32.0 seconds... I've installed and started redis via heroku run bash and the ports are correct. What could be the problem? If there is any info that would be helpful I am happy to update. -
how to ingtegrate of kafka with django with consumer ,producer, queue push ,pull from queue
''' def kfk(request): print("ala re ala") producer = KafkaProducer(bootstrap_servers='127.0.0.1:9092') producer.send('Ptopic', kafka_msg) return HttpResponse(200) ''' -
Django range filter with condition
I have a model and manager as follows, here I want to filter published posts in a date range if dates are given, otherwise I want to show only published posts. class Video(ModelMeta, models.Model): category = models.ForeignKey(VideoCategory, on_delete=models.CASCADE, related_name='videos', blank=True, null=True) video_title = models.CharField(verbose_name='Title', max_length=120, blank=True, null=True) description = models.TextField(blank=True, null=True) title = EmbedVideoField( verbose_name='Either Choose video from youtube/vimeo or', blank=True, null=True) publish = models.CharField(verbose_name='Visibility', max_length=80, choices=PUBLISH_CHOICES, default='publish') is_active = models.BooleanField(default=True) publish_start = models.DateTimeField(blank=True, null=True) publish_end = models.DateTimeField(blank=True, null=True) objects = VideoManager() class VideoManager(models.Manager): def active(self): return self.get_queryset().filter(is_active=True) def active_range(self): return self.get_queryset()\ .filter(publish_end__gte=timezone.now(), publish_start__lte=timezone.now()) \ .filter(publish='publish') def published(self): return self.active().filter(publish='publish') How I can do it, and combine the distinct values -
Django REST Multiple Nested Serializer Filter
Is there a way to filter multiple nested serializers? I have a Student serializer that displays all of the students courses. The courses display all the homework and their scores. They way I want to design the backend is that every student will receive the same homework outline but only the scores change; so to reduce duplicate data I create the scores table that points to the homework and the student. However, when I do a GET request it gets all of the students scores for that homework instance. Is there a way to filter it to only get a particular students score? I simplified my models for this example but the problem is essentially the same. In my Response, you can see "score":1 and "score":2, these belong to two different students but I want to get the specific score that relates to the a particular Student. Models class Student(models.Model): firstName = models.CharField(max_length=20) age = models.IntegerField(default=18) def __str__(self): return self.firstName class Course(models.Model): courseName = models.CharField(max_length=20) courseYear = models.IntegerField(default=2021) student = models.ManyToManyField(Student, related_name='courses') def __str__(self): return self.courseName + " " + str(self.courseYear) class Homework(models.Model): hwName = models.CharField(max_length=20) hwPossScore = models.IntegerField(default=100) course = models.ForeignKey( Course, related_name='homeworks', on_delete=models.CASCADE, null=True, blank=True) students = models.ManyToManyField(Student) … -
Django "abstract" foreign key
With Django, supposed that I am interested in the following models schema. from django.db import models class FirstModel(models.Model): x_name = models.CharField(max_length=64) x_number = models.IntegerField() y_name = models.CharField(max_length=64) y_number = models.IntegerField() def do_something_with_x(self): return f'{self.x_name} {self.x_number}' def do_something_with_y(self): return f'{self.y_name} {self.y_number}' class SecondModel(models.Model): z_name = models.CharField(max_length=64) z_number = models.IntegerField() def do_something_with_z(self): return f'{self.z_name} {self.z_number}' I could refactor the previous code as follows: class CommonModel(models.Model): name = models.CharField(max_length=64) number = models.IntegerField() def do_something(self): return f'{self.name} {self.number}' class FirstModel(models.Model): x = models.ForeignKey(CommonModel) y = models.ForeignKey(CommonModel) class SecondModel(models.Model): z = models.ForeignKey(CommonModel) However, this would create a new database table for CommonModel. Is there a way to have this refactoring only at Python level, while leaving the database schema as in the first snippet?