Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ModuleNotFoundError: No module named 'book' django
first I create a new app book and create a model class book then I messed up with that. I delete that app and create another app and run python3 manage.py runserver then I get this error enter image description here. I don't add anything in the new app. What can I do now? Is there anything more I want to specify? -
Making different views from similar (but slightly different) information?
I know there is a better way to do this, but I can't quite figure it out. I am making a web application that has a series of the same pages, based on what department and station you select. This is info that I am using later in a separate script to determine where to send a file. But right now I am using different views for each page. For example I have one view in my views.py that looks like this: views.py def FOO_station_0(request): Site_Data.station = 0 Site_Data.dept = "FOO" ctx = {} ctx['station'] = Site_Data.station if request.method == 'POST': form = my_form(request.POST) if form.is_valid(): try: Ext_Data.parsed_data = form.cleaned_data['full_scan'] saveScan() except IndexError: ctx['error_message'] = error_message return HttpResponseRedirect('/error/input') return HttpResponseRedirect(f'/confirm') else: form = my_form() ctx['form'] = form return render(request, f'scan/FOO/FOO_station.html', ctx) And another that looks like this: def BAR_station_2(request): Site_Data.station = 2 Site_Data.dept = "BAR" ctx = {} ctx['station'] = Site_Data.station if request.method == 'POST': form = my_form(request.POST) if form.is_valid(): try: Ext_Data.parsed_data = form.cleaned_data['full_scan'] saveScan() except IndexError: ctx['error_message'] = error_message return HttpResponseRedirect('/error/input') return HttpResponseRedirect(f'/confirm') else: form = my_form() ctx['form'] = form return render(request, f'scan/BAR/BAR_station.html', ctx) As you can see, they are both returning the same HTML file, this is because … -
How do II get object with the the largest value of a certain field in my Django model objects?
I'm am trying to create a view where the user will get the object with the largest value of a certain field in my Django model objects. This is my model: class LongTermCoinHistory(models.Model): coin = models.ForeignKey(Coin,on_delete=models.CASCADE) timestamp = models.BigIntegerField(default=0) price = models.FloatField() I want to get the object instance from my database that has the largest timestamp value. How do I go about doing this? -
How do I reference a model via User model in Django?
So I have two models -- UserInfo model, which references Django's built-in User model, and Article model, written by each user, as below. class UserInfo(models.Model): objects = models.Manager() this_user = models.OneToOneField(User, on_delete=models.CASCADE, related_name = 'userinfo', null=True, default=None) real_name = models.CharField(max_length=20, blank=False) class Article(models.Model): objects = models.Manager() author = models.ForeignKey(UserInfo, on_delete=models.CASCADE, related_name = 'article', null=True, default=None) body = models.CharField(max_length=20, blank=False) And here's part of my views.py. def create_ans_us(request): current_article = Article.objects.get(id=1) ... context = { 'current_article' : current_article, } return render(request, 'main/main.html', context) And in Django template tag, I'm trying to render the real_name field in UserInfo like below. <html> ... {{current_article.user_id.real_name}} </html> Now obviously, I want to render the real_name field to the template. How do I make this possible? Thanks in advance. :) -
ModuleNotFoundError: No module named 'expenseswebsite.userpreferences'
Good day dear Community! Got a following error at the PyCharm Terminal: File "C:\NewDjangoProjects\django-income-expense-website\expenseswebsite\expenses\views.py", line 9, in <module>from expenseswebsite.userpreferences.models import UserPreference ModuleNotFoundError: No module named 'expenseswebsite.userpreferences' here below my expenses\views.py file: from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from .models import Category, Expense from django.contrib import messages from django.contrib.auth.models import User from django.core.paginator import Paginator import json from django.http import JsonResponse from expenseswebsite.userpreferences.models import UserPreference here below my UserPreference\models.py file: from django.db import models from django.contrib.auth.models import User class UserPreference(models.Model): user = models.OneToOneField(to=User, on_delete=models.CASCADE) currency = models.CharField(max_length=255, blank=True, null=True) def __str__(self): return str(user)+'s preferences' Hierarchy: django-income-expense-website \ \__expenseswebsite \ \ \ \ \_authentication(migr, models, views etc..) \ \ \ \__expenses (migr, models, views etc..) \ \ \____expenseswebsite(migr, models, views etc..) \ \______templates \_________userpreferences(migr, models, views etc..) All migrations are migrated/applied successfully and there is no any red underlined text inside PyCharm Editor window, so what is wrong with that import? Thanks for any help in adavnce! -
How to change admin panel in django
I want change html, css, javascript of django admin panel because default admin panel is very ugly. How to change html, css and javascript of django admin panel. Is it possible? -
django filter in Subquery raise 'Expression contains mixed types. You must set output_field' error
I am using django orm Subquery. But when I add a specific filter parameter, FieldError: Expression contains mixed types. You must set output_field error was raised. Can I know what this error is and how to fix it? Below is the code where the error occurs, and the error occurs when is_active=True and eventcardad__isnull=False in lines 6 and 7 are added! and I'm using PostgreSQL RDBMS! personalized_event_ads_qs = CustomerPersonalization.objects.filter( customer__id__in=Customer.objects.filter(accept_marketing=True).filter(email='abc1@naver.com') ).annotate( element_ids=Subquery( Element.objects.fil is_active=True, eventcardad__isnull=False, campaign__in=campaign_qs, ).filter( majors__in=OuterRef('majors'), ).filter( Q(cities__in=OuterRef('cities')) | Q(districts__in=OuterRef('districts')) ).values( 'is_active' ).annotate( element_ids=ArrayAgg('eventcardad', distinct=True) ).values( 'element_ids' ) ) ).values( 'element_ids' ).annotate( customers=ArrayAgg('customer', distinct=True) ) -
How can I authenticate a Post Request with Token Authentication?
Right now I can successfully authenticate patch, get and delete so only the user that has access to the object can do it. But I have a simple problem: -How can I authenticate POST request? For example: User should be able to only create an ArticleImage linked to Article if both of their authors are the same, so User 2 cannot add an object to Article if User 1 is the owner. And also we want to make sure that User 2 can't do POST request in the name of User 1. Model.py class Article(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User,on_delete=models.CASCADE,related_name='articles') caption = models.CharField(max_length=250) class ArticleImage(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) image = models.FileField(upload_to='images',null=True,blank=True, validators=[validate_file_extension]) article = models.ForeignKey(Article, on_delete=models.CASCADE,null=True,blank=True, related_name='articleimages') author = models.ForeignKey(User,on_delete=models.CASCADE,related_name='articleimages') View.py class ArticleImageViewSet(viewsets.ModelViewSet): permission_classes = (IsAuthenticated,) queryset = ArticleImage.objects.all() serializer_class = ArticleImageSerializer filter_backends = [ArticleFilterBackend] Filter.py class ArticleFilterBackend(filters.BaseFilterBackend): def filter_queryset(self, request, queryset, view): return queryset.filter(article__author=request.user) -
django run websocket client in background
So when I run the WebSocket client I can no longer reach the Django app like I can't connect to 127.0.0.1:8000, here is the WebSocket file: import websocket, json, pprint from datetime import datetime socket = "wss://stream.binance.com:9443/ws/manausdt@kline_1m" def on_message(ws, msg): message = json.loads(msg) messageData = message['k'] if messageData['x']: # get_data(messageData) timestamp = float(messageData['t']) symbol = messageData['s'] interval = messageData['i'] closeprice = float(messageData['c']) openprice = float(messageData['o']) highprice = float(messageData['h']) lowprice = float(messageData['l']) datetime_ob = datetime.fromtimestamp(timestamp / 1000) data = {'timestamp': timestamp, 'symbol': symbol, 'interval': interval, 'closeprice': closeprice, 'openprice': openprice, 'highprice': highprice, 'lowprice': lowprice, 'datetime_ob': datetime_ob} print(data) def on_open(ws): print('Connected!') def on_error(wsapp, err): print("Got a an error: ", err) def runwss(): stream = websocket.WebSocketApp(socket, on_error=on_error, on_open=on_open, on_message=on_message) stream.run_forever() runwss() And I inited it in apps file: from django.apps import AppConfig class ServiceGetDataConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'service_get_data' def ready(self): import service_get_data.wss And as I said I can't reach 127.0.0.1:8000 anymore so what shall I do in this case? -
django ContentFile vs InMemoryUploadedFile
i have this code that use to compress the image,itc work, i have read many comments but i am not sure which is safer and better, ContentFile or InMemoryUploadedFile, this is my code: def save(self, *args, **kwargs): img = Image.open(self.image) img = img.convert('RGB') output = BytesIO() img = img.resize((400x400)) img.save(output, format='JPEG', quality=90) output.seek(0) #content_file = ContentFile(output.read()) #file = File(content_file) self.image = InMemoryUploadedFile(output, 'ImageField', "%s.jpg" % self.image.name.split('.')[0], 'image/jpeg', sys.getsizeof(output), None) super(Image, self).save(*args, **kwargs) with InMemoryUploadedFile, if the size is greater than 2.5mb, the TemporaryFileUploadHandler will be used or the connection will drop -
razorpay.errors.BadRequestError: Amount is/are not required and should not be sent
I am integrating razorpay payment gateway in my django project and dont know why i am getting this error.:-Amount is/are not required and should not be sent. i checked my whole code but did not find any solution This is Traceback, In traceback window i am getting Exception Value: Amount is/are not required and should not be sent Traceback (most recent call last): File "D:\Project 3\test\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "D:\Project 3\test\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\Project 3\payment\paymentapp\views.py", line 13, in index payment = client.order.create({'Amount':amount, 'currency':'INR','payment_capture':'1'}) File "D:\Project 3\test\lib\site-packages\razorpay\resources\order.py", line 71, in create return self.post_url(url, data, **kwargs) File "D:\Project 3\test\lib\site-packages\razorpay\resources\base.py", line 20, in post_url return self.client.post(url, data, **kwargs) File "D:\Project 3\test\lib\site-packages\razorpay\client.py", line 155, in post return self.request('post', path, data=data, **options) File "D:\Project 3\test\lib\site-packages\razorpay\client.py", line 136, in request raise BadRequestError(msg) Exception Type: BadRequestError at / Exception Value: Amount is/are not required and should not be sent This is Views.py from django.shortcuts import render import razorpay from .models import coffee # Create your views here. def index(request): if request.method=='POST': Name = request.POST.get("Name") amount = int(request.POST.get("Amount")) * 100 client = razorpay.Client(auth=("rzp_test_YhfEhfejrkkjdkfju","t5MRPkjfijdh23845kejkej")) payment = client.order.create({'Amount':amount, 'currency':'INR','payment_capture':'1'}) print(payment) Coffee = coffee(Name=Name, Amount=amount , payment_id = … -
Returning less items
Hi I have a problem during my django-app development. I wanted to add cart feature to my e-commerce website but I have a problem. I get an error get() returned more than one Item -- it returned 4! I bet it is caused by line item = Item.objects.get_or_create(Item)` I have not specified ID and I have no idea how to do it or I should just create slugField and pass there the Slug? views.py @login_required def add_to_cart(request, *args, **kwargs): item = Item.objects.get_or_create(Item) order_item,created = OrderItem.objects.get_or_create(active=True) order,created = Order.objects.get_or_create(order_user=request.user, item=item, order_items=order_item) order.quantity += 1 order.save() messages.success(request, "Cart updated!") return redirect('cart-page') models.py class OrderItem(models.Model): order_item = models.ForeignKey(Item, on_delete=CASCADE, null=True) quantity = models.IntegerField(default=1) class Order(models.Model): order_user = models.ForeignKey(User, on_delete=CASCADE) order_items = models.ManyToManyField(OrderItem) ordered = models.BooleanField(default=False) total = models.DecimalField(default=0.00, decimal_places=2, max_digits=11) -
Django DRF and generic relations: how to obtain content_object field from API response?
I have implemented Generic Relations in Django DRF following the official guide and it works well, apart from the fact that I cannot seem to obtain the field content_object from my API response. Basically, I have a model called Document that can either be related to a model called Folder or a model called Collection. class Document(models.Model): limit = models.Q(app_label='folders', model='folder') | models.Q( app_label='collections', model='collection') title = models.CharField(max_length=500) # Field necessari per la Generic Relation content_type = models.ForeignKey( ContentType, on_delete=models.CASCADE, null=True, blank=True, limit_choices_to=limit) object_id = models.PositiveIntegerField(null=True, blank=True) content_object = GenericForeignKey( 'content_type', 'object_id') category = models.CharField(max_length=30, blank=True, null=True) def __str__(self): return self.title class Folder(models.Model): ... documents = GenericRelation(Document) def __str__(self): return self.title class Collection(models.Model): ... documents = GenericRelation(Document) def __str__(self): return self.title Here are my serializers: class ContentObjectRelatedField(serializers.RelatedField): def to_representation(self, value): if isinstance(value, Folder): serializer = FolderSerializer(value) elif isinstance(value, Collection): serializer = CollectionSerializer(value) else: raise Exception('Unexpected type of object') return serializer.data class DocumentSerializer(serializers.ModelSerializer): class Meta: model = Document fields = ('id', 'title', 'content_type', 'object_id', 'category') class FolderSerializer(serializers.ModelSerializer): documents = DocumentSerializer(many=True, read_only=True) class Meta: model = Folder fields = ("id", "title", "description", "documents") depth = 1 (Collection serializer is essentially the same ad the Folder serializer, with its own fields). I was … -
How i can integrate BigBlueButton into my Django website
I'm trying to use an API called BigBLueButton in my website, and after a little researches, i figured how to install it in my project using the command pip install django-bigbluebutton. I add it to my INSTALLED-APP in setting.py. Until this step, everything is OK and i have no errors. But i don't know how use its models and its views and how to show it in my website. Does anyone have an idea of the next steps? Thank you everyone. -
"BulkIndexError at /admin/books/address/add/" Django_rest_framework + ElasticSearch
I am trying to implement Elastic Search with django rest framework. I have implemented it without nested fields(Foreign Keys). But now stuck while trying to work with nested fields. I am following this documentation django-elasticsearch-dsl-drf. From django admin panel I am able to create City and Country model but when I create Address model I get this error: ('1 document(s) failed to index.', [{'index': {'_index': 'address', '_type': '_doc', '_id': '7', 'status': 400, 'error': {'type': 'illegal_argument_exception', 'reason': 'The [standard] token filter has been removed.'}, 'data': {'id': 7, 'street': '20', 'house_number': '155', 'appendix': 'sonething', 'zip_code': '123', 'city': {'name': 'Lahore', 'info': 'this is my city', 'location': {'lat': Decimal('31.504828100000000'), 'lon': Decimal('74.323542500000000')}, 'country': {'name': 'Pakistan', 'info': 'this is my country', 'location': {'lat': Decimal('31.504828100000000'), 'lon': Decimal('74.323542500000000')}}}, 'location': {'lat': Decimal('31.5048281'), 'lon': Decimal('74.3235425')}}}}]). Thanks in advance for helping and your addition to my knowledge. I am sharing my files with you for better understanding. Models.py from django.db import models from six import python_2_unicode_compatible @python_2_unicode_compatible class Country(models.Model): """Country.""" name = models.CharField(max_length=255) info = models.TextField(null=True, blank=True) latitude = models.DecimalField(null=True, blank=True, decimal_places=15, max_digits=19, default=0) longitude = models.DecimalField(null=True, blank=True, decimal_places=15, max_digits=19, default=0) class Meta(object): """Meta options.""" ordering = ["id"] def __str__(self): return self.name @property def location_field_indexing(self): """Location for indexing. Used in Elasticsearch … -
Django / DRF - Got AttributeError when attempting to get a value for field `users_answers_set` on serializer `TestTakerSerializer`
everyone. Working with DRF gave me this error: models.py: class TestTaker(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) test = models.ForeignKey(Test, on_delete=models.CASCADE) class UsersAnswers(models.Model): test_taker = models.ForeignKey(TestTaker, on_delete=models.CASCADE) question = models.ForeignKey(Question, on_delete=models.CASCADE) answer = models.ForeignKey(Answer, on_delete=models.CASCADE) serializers.py class UsersAnswersSerializer(serializers.ModelSerializer): class Meta: model = UsersAnswers fields = "__all__" class TestTakerSerializer(serializers.ModelSerializer): users_answers_set = UsersAnswersSerializer(many=True) class Meta: model = TestTaker fields = "__all__" And I get: Got AttributeError when attempting to get a value for field `users_answers_set` on serializer `TestTakerSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `TestTaker` instance. Original exception text was: 'TestTaker' object has no attribute 'users_answers_set'. I tried to add "source" parameter to users_answers_set, but nothing changed. Thank you. -
pysolr is taking time first time after the solr restart
pysolr is taking time first time after the solr restart. Scenario is like this. 1)Restart Solr server 2)Execute the query directly in solr is taking 4 sec 3)when we are trying to execute the same query using pysolr, it is taking 300 seconds or more for the first time. After refreshing it is taking only less than 2 sec. When I check the pysolr code the time is taking in the below code. resp = requests_method(url, data=bytes_body, headers=headers, files=files, timeout=self.timeout, auth=self.auth) 4)Can anybody help me in getting the out faster first time also. I think this abnormal because executing the query directly in Solr is taking very few seconds. -
How to calculate average of some field in Dango models and send it to rest API?
I want to count the average of ratings ( in Reviews model ) and send it to my API. Models.py from django.db import models from adminuser.models import Categories from accounts.models import UserAccount as User from django.core.validators import MaxValueValidator, MinValueValidator # Create your models here. class Gigs(models.Model): title = models.CharField(max_length=255) category = models.ForeignKey(Categories , on_delete=models.CASCADE) price = models.DecimalField(max_digits=6, decimal_places=2) details = models.TextField() seller = models.ForeignKey(User,default=None, on_delete=models.CASCADE) class Reviews(models.Model): rating = models.SmallIntegerField( default=0,validators=[MaxValueValidator(5),MinValueValidator(1)]) comment = models.CharField(max_length=500) item = models.ForeignKey(Gigs , on_delete=models.CASCADE) buyer = models.ForeignKey(User ,default=None, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) Views.py from django.shortcuts import render from .models import Gigs,Reviews from .serializers import GigsSerializer,ReviewsSerializer from rest_framework.generics import GenericAPIView from rest_framework.mixins import ListModelMixin, CreateModelMixin , RetrieveModelMixin , DestroyModelMixin, UpdateModelMixin from rest_framework.permissions import AllowAny # Create your views here. #List and create (pk not required) class GigsListAPI(GenericAPIView, ListModelMixin ): def get_queryset(self): username = self.kwargs['user'] return Gigs.objects.filter(seller=username) serializer_class = GigsSerializer permission_classes = (AllowAny,) def get(self, request , *args, **kwargs): return self.list(request, *args, **kwargs) class GigsListCategorywise(GenericAPIView, ListModelMixin ): def get_queryset(self): SearchedCategory = self.kwargs['category'] return Gigs.objects.filter(category=SearchedCategory) serializer_class = GigsSerializer permission_classes = (AllowAny,) def get(self, request , *args, **kwargs): return self.list(request, *args, **kwargs) class GigsListAll(GenericAPIView, ListModelMixin ): queryset = Gigs.objects.all() serializer_class = GigsSerializer permission_classes = (AllowAny,) def get(self, request , … -
how can i access a static django image in javascript
i want to access the django static folder via javascript. I have stored a folder structure and pictures in the static folder. I get the folder and the picture name via an Ajax and now I want to display the picture using javascript. I used django tag to write all picture urls into an array and then read them out. <script> var ImagesURL = [ "{% static "/A/A_ol1.png" %}", "{% static "/A/A_ol2.png" %}", "{% static "/A/A_ol3.png" %}", "{% static "/A/A_ol4.png" %}", "{% static "/A/A_ol5.png" %}", "{% static "/A/A_ol6.png" %}", ... ]; </script> that works pretty well too. it's just too static for me. Now that I have more and more pictures and a more complex structure of the folders I would prefer to use the ajax, so that I can put together the url from the names and folders passed ... is there a trick? -
Cannot set a very simple object attribute to an object with a many:many relationship
I'm learning django and cannot seem to just literally add a message to an automation. I have a POST method and I should be able to add a message to an automation (both Message and Automation classes have a many to many relationship). This is how the automation is logged just before trying to add the message: before {'_state': <django.db.models.base.ModelState object at 0x7fbd47a27370>, 'id': 9, 'name': 'test bobbie automation', 'description': 'a test bobbie automation', 'account_id': 34, 'date_created': datetime.datetime(2021, 8, 27, 8, 55, 52, 723100, tzinfo=<UTC>)} It has no messages, but the class denotes a many:many relationship between messages and automations, so I see no reason why it cannot be added. What am I doing wrong here? I’ve tried all of these but to no avail: # automation.messages.set(msg) # automation.messages.append(msg) # automation.messages.add(msg) # does not work # automation['messages'] = msg automation.messages.set(msg) Where the latest attempt fails with TypeError: 'Message' object is not iterable. View: @login_required(login_url='login') @allowed_users(allowed_roles=['admin', 'customer'], own_account_only=True) def automation_add_message(request, pk, automation_id): account = Account.objects.get(id=pk) automation = Automation.objects.get(id=automation_id) if request.method == 'POST': msgId = request.POST.get('message_id') msg = Message.objects.get(id=msgId) print('before', automation.__dict__) # automation.messages.set(msg) # error here @todo # automation.messages.append(msg) # automation.messages.add(msg) # does not work # automation['messages'] = msg # also fails … -
JQuerie user variable between {} [duplicate]
The value : termid is a value received from a form but I can figure out the use him between. {% url 'terminals_update_view' site.id termid %} the site.id is from the django form and works well <script type="text/javascript"> $(document).ready(function () { $("button.add-comment-button3").click(function (e) { termid = $(this).val(); console.log(my_button); $.ajax({ success: function (data) { $('#table_body').html('').load("{% url 'terminals_update_view' site.id termid %}"); } }); }); }); </script> -
Having a problem while trying to code through the book: "Django for Beginners" by William S. Vincent
The error message I am getting is: AttributeError: module 'django.contrib' has no attribute 'staticfilespages' whenever I run the command python manage.py runserver in Windows PowerShell I'm assuming the problem is in this code because it's the only place I can find django.contrib, but Visual Studio Code isn't pointing out any problems. from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('pages.urls')) ] -
Django auto increment in form
Lets say I have this model.py: class Order(models.Model): delivery = models.BooleanField() I have this form.py: class OrderForm(ModelForm): class Meta: model = Order fields = ["delivery"] And I have this views.py: def get_order(request): if request.method == "POST": form = OrderForm(request.POST) if form.is_valid(): order_instance = form.cleaned_data["delivery"] return HttpResponseRedirect("/end") else: form = OrderForm() return render(request, "order.html", {"form": form}) And the HTML page show form page. With this code my program will tell me that he is not happy because I am trying to use delivery (a boolean) for a id field because Django automatically create a id field for each model. This field is supposed to auto increment but with form it doesnt seem to work. So how can I force him to auto increment ? -
Why my django form create a new object for the wrong model
I'm creating a list with hierarchical data base Title -> Category -> Subcategory by using proxy (according to this video). User first see a table with titles name and status, then he can click on one of titles to go to the next page that has a table of categories name and status and then he can click on one of these categories to go to the next page with table of subcategories name and status. I want to create a form that will add a new name and a new status for my category or subcategory. But whenever I submit the form, it doesn't matter if it's TitleForm or CategoryForm or SubcategoryForm, I always get a new Title object but never Category or Subcategory object. I've checked my code several times but I couldn't find any issue, everything seems correct. Could someone explain me what the problem is and how can I fix it? models.py from django.db import models from .managers import TitleManager, CategoryManager from model_utils.fields import StatusField from model_utils import Choices class Node(models.Model): name = models.CharField(max_length=70) STATUS = Choices("Na bieżąco", "Porzucone", "Wymaksowane", "Planowane", "W trakcie", "Obejrzane") status = StatusField(choices_name='STATUS') parent = models.ForeignKey( 'self', on_delete=models.CASCADE, related_name='children', null=True, blank=True, ) … -
Django Rest Framework : How to define a ModelSerializer representing a Model A, when A depends itself of other models B and C?
Let's say we have three Models : ModelA, related to ModelB and ModelC. ModelA is defined as : class ModelA(models.Model): field_b = models.ForeignKey(ModelB, on_delete=models.CASCADE) field_c = models.ForeignKey(ModelC, on_delete=models.CASCADE) other_field = models.CharField(max_length=30) class Meta: constraints = [ models.UniqueConstraint(fields=['field_b', 'field_c'], name='unique_modelA') ] How to generate a ModelASerializer instance from instances of ModelB and ModelC ? Then, will there be a serialized representation of field_b and field_c into ModelASerializer ? The UniqueConstraint will it be checked when calling .is_valid() onto ModelASerializer instance ? I tried the following : class ModelASerializer(serializers.ModelSerializer): field_b = ModelBSerializer(read_only=True) field_c = ModelCSerializer(read_only=True) other_field = serializers.CharField(required=False) class Meta: model = ModelA fields = ('field_b', 'field_c', 'other_field',) validators = [ UniqueTogetherValidator( queryset=ModelA.objects.all(), fields=['field_b', 'field_c'], message='A Model A instance for this couple of ModelB and ModelC instances already exists.' ) ] def create(self, validated_data): """ Create and return a new `ModelA` instance, given the validated data. """ return ModelA.objects.create(**validated_data) def update(self, instance, validated_data): """ Update and return an existing `ModelA` instance, given the validated data. """ instance.other_field= validated_data.get('other_field', instance.other_field) instance.save() return instance But I cannot find any way to create the serializer : model_b = ModelB() model_c = ModelC() model_b.save() model_c.save() other_field = "Dummy content" First try model_a_serializer = ModelASerializer(model_b, model_c, other_field) …