Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Scrapy Spider stops before crawling anything
So I have a django project and a views.py from which I want to call a Scrapy spider if a certain condition is met. The crawler seems to be called just fine but terminates so quickly that the parse function is not called (that is my assumption at least) as shown below: 2020-11-16 18:51:25 [scrapy.crawler] INFO: Overridden settings: {'BOT_NAME': 'products', 'NEWSPIDER_MODULE': 'crawler.spiders', 'SPIDER_MODULES': ['crawler.spiders.my_spider'], 'USER_AGENT': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, ' 'like Gecko) Chrome/80.0.3987.149 Safari/537.36'} 2020-11-16 18:51:25 [scrapy.extensions.telnet] INFO: Telnet Password: ****** 2020-11-16 18:51:25 [scrapy.middleware] INFO: Enabled extensions: ['scrapy.extensions.corestats.CoreStats', 'scrapy.extensions.telnet.TelnetConsole', 'scrapy.extensions.logstats.LogStats'] ['https://www.tesco.com/groceries/en-GB/products/307358055'] 2020-11-16 18:51:26 [scrapy.middleware] INFO: Enabled downloader middlewares: ['scrapy.downloadermiddlewares.httpauth.HttpAuthMiddleware', 'scrapy.downloadermiddlewares.downloadtimeout.DownloadTimeoutMiddleware', 'scrapy.downloadermiddlewares.defaultheaders.DefaultHeadersMiddleware', 'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware', 'scrapy.downloadermiddlewares.retry.RetryMiddleware', 'scrapy.downloadermiddlewares.redirect.MetaRefreshMiddleware', 'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware', 'scrapy.downloadermiddlewares.redirect.RedirectMiddleware', 'scrapy.downloadermiddlewares.cookies.CookiesMiddleware', 'scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware', 'scrapy.downloadermiddlewares.stats.DownloaderStats'] 2020-11-16 18:51:26 [scrapy.middleware] INFO: Enabled spider middlewares: ['scrapy.spidermiddlewares.httperror.HttpErrorMiddleware', 'scrapy.spidermiddlewares.offsite.OffsiteMiddleware', 'scrapy.spidermiddlewares.referer.RefererMiddleware', 'scrapy.spidermiddlewares.urllength.UrlLengthMiddleware', 'scrapy.spidermiddlewares.depth.DepthMiddleware'] views.py def get_info(): url = data[product]["url"] setup() runner(url) @wait_for(timeout=10.0) def runner(url): crawler_settings = Settings() configure_logging() crawler_settings.setmodule(my_settings) runner = CrawlerRunner(settings=crawler_settings) d = runner.crawl(MySpider, url=url) my_spider.py import scrapy from scrapy.loader import ItemLoader from itemloaders.processors import TakeFirst from crawler.items import ScraperItem class MySpider(scrapy.Spider): name = "myspider" def __init__(self, *args, **kwargs): link = kwargs.get('url') self.start_urls = [link] super().__init__(**kwargs) def start_requests(self): yield scrapy.Request(url=self.start_urls[0], callback=self.parse) def parse(self, response): do stuff Can anyone guide me towards why this is happening and how I can … -
django_migrations table and several apps / databases
I have 3 apps and 3 databases setup in my Django project. Each app is related to its own DB so I created a DB router and all seems to work fine but I still see the migrations of every app being recorded in the django_migrations table of each DB. Is that the normal behavior? -
Why does AWS give me an error with regions?
This has happened to me everytime i connect my django to aws S3 buckets, normally it goes away for some reason which I don't know and would like to know how to prevent it from happening again. my settings: AWS_S3_REGION_NAME = 'eu-west-3' AWS_S3_SIGNATURE_VERSION = 's3v4' AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None (I am not including the access key id, secret access key and bucket name, they are not necessary) and my Bucket regiion is: EU (Paris) eu-west-3 my full error message: <Code>AuthorizationQueryParametersError</Code> <Message>Error parsing the X-Amz-Credential parameter; the region 'us-east-1' is wrong; expecting 'eu-west-3'</Message> <Region>eu-west-3</Region> I have seen online explanations but none seemed to solve it. As I said this has happened to me multiple times and always goes away for no reason! I would like to know what causes it rather than leaving it up to chance. Does anyone have any idea why? -
How to manage sessions with Firebase Authentication, React SPA and Django Rest Framework Backend?
I think the most important details are in the title. I'm well aware that this combination is mostly not recommended. Therefore I would be very happy if someone might come up with an alternative way of solving the detailed problem that follows: The SPA and the Backend-API are running on different hosts provided by Google Cloud Services (Flexible Google App Engine). We have a user account that is supposed to run on several devices. One device will be used as day-to-day operations in a store by the manager. When the store owner (who might be different from the manager) wants to change Store-Properties he should be able to login on a different device and request a TAN for an admin session. With Firebase Custom Claims we can make the admin session available to the account, but this would mean that the store manager can also access the properties in the current session. This shouldn't be possible. That's why we need a session-based management of user access. The only option I see this far is having Django assigning sessions, which means we have to mess with CORS and reduce Django's security measures. The resources available to me generally and on Google … -
django datefield auto_now = true dont work
I have this table in my model, i just want that if the data is updated the modifyDate field will automatict updated. note: i am not using the adminsite to update data class FmCustomerEmployeeSupplier(models.Model): dateSubmitted = models.DateField(auto_now_add=True, null=True, blank=True) lastname = models.CharField(max_length=500, blank=True, null=True) firstname = models.CharField(max_length=500, blank=True, null=True) middleInitial = models.CharField(max_length=500, blank=True, null=True) bodyTemperature = models.FloatField(blank=True, null=True) modifyDate = models.DateField(auto_now=True, blank=True, null=True) modifyBy = models.CharField(max_length=500, blank=True) @property def is_past_due(self, *args, **kwargs): return date.today() > self.modifyDate class Meta: verbose_name_plural = "50. Customer's List of Employees, Suppliers and visitors" -
Best way of saving edit history in postgresql with Django
A lot of times I've had the need to know "who updated what" in my database tables. I've always done this by creating similar tables with extra fields, for instance "updated_by" and "time_updated" which store the user who edited the record and when they did it respectively. Here's a simple example; CREATE TABLE student ( id SERIAL PRIMARY KEY, first_name varchar(100) PRIMARY KEY, last_name varchar(100), ); CREATE TABLE student_edit_history ( id SERIAL PRIMARY KEY, student_id integer, first_name varchar(100) PRIMARY KEY, last_name varchar(100), updated_by varchar(100), time_updated timestamptz, ); Is there a better way of achieving the same in PostgreSQL without creating new tables? Does Django provide a way of saving edit history? -
one to Many relationships in django
I'm trying to display multiple fields on a single line in django admin. it must be like so: Listaflor: Flora2Estado object (1) Familia object (1) Flora2Estado object (2) Flora2Estado object (1) Flora2Estado object (1) Familia object (1) My db looks like this: Estados: Estado_id Estado_nome Flora2Estado: estado_id especie_id models.py: especie = models.OneToOneField(Flora2Estado, models.DO_NOTHING, primary_key=True)``` -
Show multiple fields within a row in Django Admin
there. I've been struggling with a situation in Django/Mysql. There is this column in a table that has a primary key and foreign key at the same time. This column has a one to many relation with an intermediary table. It's a list of states linked to plant species. Some species can be found in more than one state. Species (table 1) Columns: Species_id | specie_name Species_to_states (table 2) Columns: Species_id | State_id States (table 3) Columns: States_id, State_name The point is that it's being shown only one object in django admin. So i would like to show multiple fields within a row. Can someone help me with that issue? Thank you so much -
list() missing 1 required positional argument: 'slug'
In my Django projects to effectively teake a random objects form queryset I have always used: random_cars = random.sample(list(Cars.objects.all()), 3) In the current project, this is raised by an exception: list() missing 1 required positional argument: 'slug' I tried to add the slug = None attribute but to no work random_cars = random.sample(list(Cars.objects.all(), slug=None), 3) it's return uerySet' object has no attribute 'META' How can I efficiently get a random query slice without error. Why can I get this error? -
Trim off N bytes from audio file using SoX / FFmpeg etc, on Windows?
My team accidentally on purpose clicked NO when Audacity asked to save the recording. So I left with bunch of *.au files, after using recovery program. Some of them did have header and still open-able with audacity itself (example : this one), and some other are just complete nonsense, sometimes having the header filled with text from random javascript or HTML code (like this one). Probably hard disk half overwritten with browser cache? I don't know. And at this point, I almost don't care. The audacity is on default settings, with sample rate 44100Hz. I can open a-113.au using audacity, from standard open files. I also was able to achieve open files using "Open RAW files" from Audacity, using this settings : so I assume header takes 12384 bytes. Now, how do I trim 12384 bytes from the file when opened as RAW, with either SoX or ffmpeg? because if I open it as RAW with 0 offset (default settings), it will add the header as a noise. Current ffmpeg command I used : ffmpeg.exe -f f32le -ar 44.1k -ac 1 -i source destination Current sox command I used : sox -t raw --endian little --rate 44100 -b 1 -b … -
django-oauth-toolkit request object don`t have custom attribute added by middleware
I have created a middleware and added my_name attribute in request and accessing this in custom authentication class but getting attribute error. class MyMainMiddleware(MiddlewareMixin): def process_request(self, request): request.my_name = "my name" added middleware MyMainMiddleware in settings MIDDLEWARE = [ "apps.middleware.MyMainMiddleware", "django.middleware.security.SecurityMiddleware", 'corsheaders.middleware.CorsMiddleware', "django.contrib.sessions.middleware.SessionMiddleware", "oauth2_provider.middleware.OAuth2TokenMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", ] AUTHENTICATION_BACKENDS = [ "apps.accounts.backends.ModelBackend", ] views.py from oauth2_provider.oauth2_validators import OAuth2Validator from django.contrib.auth import authenticate class OAuth2Validator(OAuth2Validator): def validate_user(self, username, password, client, request, *args, **kwargs): """ Check username and password correspond to a valid and active User """ u = authenticate(request, username=username, password=password) if u is not None and u.is_active: request.user = u return True return False class CustomTokenView(TokenView): validator_class = OAuth2Validator @method_decorator(sensitive_post_parameters("password")) def post(self, request, *args, **kwargs): return super(CustomTokenView, self).post(request, *args, **kwargs) curl request for token curl -X POST \ http://localhost:8000/authenticate/token/ \ -F grant_type=password \ -F username=<user> \ -F password=<password> \ -F client_id=<client_id> \ -F client_secret=<client_secret> Below is the traceback File "/usr/local/lib/python3.7/site-packages/oauthlib/oauth2/rfc6749/grant_types/resource_owner_password_credentials.py", line 184, in validate_token_request request.password, request.client, request): File "/code/apps/accounts/views.py", line 39, in validate_user u = authenticate(request, username=username, password=password) File "/usr/local/lib/python3.7/site-packages/django/contrib/auth/__init__.py", line 73, in authenticate user = backend.authenticate(request, **credentials) File "/code/apps/accounts/backends.py", line 16, in authenticate if username is None: File "/usr/local/lib/python3.7/site-packages/oauthlib/common.py", line 436, in __getattr__ raise AttributeError(name) AttributeError: my_name … -
django datefield auto_now = true dont work
I have this field in my models , i just want that if the data is update on that table, the django will trigger or the modifyDate will automatic updated as well. note: i am not using the adminsite to update data class FmCustomerEmployeeSupplier(models.Model): dateSubmitted = models.DateField(auto_now_add=True, null=True, blank=True) lastname = models.CharField(max_length=500, blank=True, null=True) firstname = models.CharField(max_length=500, blank=True, null=True) middleInitial = models.CharField(max_length=500, blank=True, null=True) bodyTemperature = models.FloatField(blank=True, null=True) modifyDate = models.DateField(auto_now=True, blank=True, null=True) modifyBy = models.CharField(max_length=500, blank=True) @property def is_past_due(self, *args, **kwargs): return date.today() > self.modifyDate class Meta: verbose_name_plural = "50. Customer's List of Employees, Suppliers and visitors" -
using DRF with an other authentication backend
i am using keycloak as IAM for my project which is a multi service project. i want to use django rest framework for my django service. i have managed to make authentication work and request.user returns an instance of User from django.contrib.auth.models, the problem is drf creates a new request object for the view, and the user authenticated by keycloak backend set in AUTHENTICATION_BACKENDS is lost, to solve this problem i have made a permission class like the following: class ClientRoleBasedPermission(permissions.BasePermission): role = "create_room" def has_permission(self, request, view): if self.role in request._request.user.get_all_permissions(): return True return False i am using this simple view to test things class ListUsers(APIView): """ View to list all users in the system. * Requires token authentication. * Only admin users are able to access this view. """ permission_classes = [CreateRoomPermission] permission = "create_room" def get(self, request, format=None): """ Return a list of all users. """ usernames = [user.username for user in User.objects.all()] return Response(usernames) is there a better way to solve this issue ? -
Django makemigration error No module named 'qrcode.settings'
I am trying to set up a new project on my windows 10 64 bit pc While doing python manage.py makemigrations I keep getting ModuleNotFoundError: No module named 'qrcode.settings' I have installed all the dependencies successfully, running the cmd in venv. I looked for this particular issue, but couldn't find the solution. I am using Python 3.9. The dependencies are asgiref==3.2.7 certifi==2020.4.5.1 cffi==1.14.0 chardet==3.0.4 cryptography==2.9 Django==3.0.5 djangorestframework==3.11.0 djangorestframework-jwt==1.11.0 idna==2.9 mysqlclient==1.4.6 pycparser==2.20 PyJWT==1.7.1 PyMySQL==0.9.3 PyPDF2==1.26.0 pytz==2019.3 requests==2.23.0 six==1.14.0 sqlparse==0.3.1 urllib3==1.25.9 paypalrestsdk==1.13.1 The error is as follows Traceback (most recent call last): File "C:\Users\zubai\Downloads\SaveTreesQR\env\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\zubai\Downloads\SaveTreesQR\env\lib\site-packages\django\core\management\base.py", line 368, in execute self.check() File "C:\Users\zubai\Downloads\SaveTreesQR\env\lib\site-packages\django\core\management\base.py", line 392, in check all_issues = checks.run_checks( File "C:\Users\zubai\Downloads\SaveTreesQR\env\lib\site-packages\django\core\checks\registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\zubai\Downloads\SaveTreesQR\env\lib\site-packages\django\core\checks\templates.py", line 22, in check_setting_app_dirs_loaders for conf in settings.TEMPLATES File "C:\Users\zubai\Downloads\SaveTreesQR\env\lib\site-packages\django\conf\__init__.py", line 83, in __getattr__ self._setup(name) File "C:\Users\zubai\Downloads\SaveTreesQR\env\lib\site-packages\django\conf\__init__.py", line 70, in _setup self._wrapped = Settings(settings_module) File "C:\Users\zubai\Downloads\SaveTreesQR\env\lib\site-packages\django\conf\__init__.py", line 177, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Program Files\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 'qrcode.settings' During handling of the … -
Send list elements to POST form
I have a page where the user selects values from a <li> object and drops them in another <li> object. (This is done using jQueryUI) I'd like to send to the backend via a POST request the elements that the user selects. Currently if I print the session (print(request.POST)) it doesn't show the <li> objects. To my understanding this is correct because you'd need the <input> tag. How can I achieve this kind of behaviour? I've seen this question which is the same problem, but the answer is not complete, also it's somewhat old. View def page(request): li_dict = { 'a': 'A', 'b': 'B', 'c': 'C', 'd': 'D', } # ... # POST logic if request.method == "POST": # do stuff.. #... context = {'groups_variable_list': li_dict} return render(request, 'page.html', context=context) Html <div> <ul id="sortable1" class="connectedSortable"> {% for key, value in groups_variable_list.items %} <li value={{key}}>{{value}}</li> {% endfor %} </ul> </div> <div> <form action="" method="POST"> {% csrf_token %} <ul id="sortable2" class="connectedSortable"> <!-- list filled by user with drag&drop --> </ul> <input type="submit" name="Submit"> <!-- button for POST request --> </form> </div> <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script> <!-- jQuery UI for Sortable function --> <script> // sortable jQueryUI $(document).ready(function() { $( "#sortable1, #sortable2" ).sortable({ … -
Django: ROOT_URLCONF: How to distinguish between two folders with same name with two 'urls.py'?
settings.py: From the picture, you can see that there is the path trydjango/urls.py and trydjango/trydjango/urls.py. I used the latter to import my views as the FreeCodeCamp tutorial said to do. ROOT_URLCONF is set to: ROOT_URLCONF = 'trydjango.urls'. I can't go to any of my webpages in the code below for some reason. trydjango/trydjango/urls.py: I attempted to move what I had in 'trydjango/trydjango/urls.py' to 'trydjango/urls.py' and this still did not work. I also attempted to change ROOT_URLCONF to: ROOT_URLCONF = 'trydjango.trydjango.urls',but this did not work either. What should I do here? Please advise. -
page() missing 1 required positional argument: 'number' in django
So, I am trying to add pagination to my django website. Here is the code for my view function that handles pagination: def index(request): object_list = Post.published.all() latest_post = object_list.last() paginator = Paginator(object_list, 3) page = request.GET.get('page') try: posts = Paginator.page(page) except PageNotAnInteger: posts = paginator.page(1) except EmptyPage: posts = paginator.page(paginator.num_pages) return render(request, 'blog/index.html',{ 'posts':posts, 'latest_post':latest_post, 'page':page, }) I am getting an error on line 11, inside the try block. Where is the error? -
How can I build a web app using python django and a ready MYSQL workbench database? [closed]
I am fairly new to this. I created a MySQL Workbench database populated with the data and tables I want. I now want to make a Small website using django web app to get from or post onto my database using MySQL queries. I tried finding tutorials but I got lost. (I must use above methods) I am not sure what I need to do. What I have done is: Install django and start a project edit settings.py in my django project to mysql Trying to install mysqlclient What should happen next and what do I need to do and what will I use? It’s a fairly small project. -
name 'validated_data' is not defined
I am trying to serialize multiple images posted for article in JSON format in DRF class ArticleImagesViewSerializer(serializers.ModelSerializer): class Meta: model = ArticleImages fields = ('id','image') def create(self, validated_data): return ArticleImages.objects.create(**validated_data) class ArticleViewSerializer(serializers.ModelSerializer): images = ArticleImagesViewSerializer(required=False,many=True) class Meta: model = Article fields = ('id','author','caption','images') def create(self, validated_date): images = self.context['request'].FILES.getlist('images') articlefinal = Article.objects.create(**validated_data) for image in list(images): m2 = ArticleImages(article=articlefinal, images= image) m2.save() return articlefinal But i am getting an error that is saying articlea = Article.objects.create(**validated_data) NameError: name 'validated_data' is not defined Does anybody know why? -
Query in query in django?
I'm trying to achieve a query but I'm just unable to do it. I have 3 entities here: Clients: class Client(LogsMixin, models.Model): """Model definition for Client.""" company_name = models.CharField("Nombre de la empresa", max_length=150, default="Nombre de empresa", null=False, blank=False) user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) Courses: class Course(LogsMixin, models.Model): """Definición del modelo de Proveedor.""" name = models.CharField("Nombre del curso", null=False, default="", max_length=200) Consumptions: class Consumption(LogsMixin, models.Model): """Definición del modelo de Consumos""" client = models.ForeignKey('authentication.Client', verbose_name=("Cliente"), null=True, default=None, on_delete=models.SET_DEFAULT) course = models.ForeignKey(Course, verbose_name=("Curso"), null=True, default=None, on_delete=models.SET_DEFAULT) I want to get a list with the 10 most sold courses for the client that visit the page. I want to show the client the name of the course and the number of consumptions that he has done with that course. In every consumption there is a course and a client associated. Could someone give me a hand? -
How to create two object instances from two different models with a single POST request?
I am learning the Django-Rest Framework. I want to create an object instance for both my Story model and my File model with a single post request. So the incoming data contains a title and a file. I want then to create a story object with a title and the image field contains a reference (fk) to the id of the file instance. In the File model a own instance of File is created with the incoming file data. # File Model class File(models.Model): file = models.FileField(upload_to='audio_stories/', null=True, default='some_value') # Story Model class Story (models.Model): title = models.CharField(max_length=100,blank=True) image = models.ForeignKey(File,on_delete=models.CASCADE, blank=True, default=None) # Story Serializer class StoryCreateUpdateSerializer (serializers.ModelSerializer): image = serializers.FileField() class Meta: model = Story fields = ('title','image') def create(self, validated_data): image = validated_data.pop('image') title = validated_data.pop('title') image_instance = File.objects.create(file=image) story_instance = Story.objects.create(title=title, image=image_instance) return story_instance # File Serializer class TestFileSerializer (serializers.ModelSerializer): class Meta: model = File fields = ('__all__') If I send the formdata via Postman to my server it responses with "image": ["This field is required."]. If this is an obvious mistake, I apologize in advance. I am grateful for any clarification. -
Django - Implement "Remember me" after login
Could you please point me to the right direction of how to implement Remember me in my website. I read a couple of articles of how to implement but i'm more confused than point me to the right direction. I've configured the following: forms.py first_name = forms.RegexField(regex=r'^[a-zA-Z]+$', max_length=30, label=_("first name"), error_messages={'invalid': _("Wrong First Name, use only letters")}) last_name = forms.RegexField(regex=r'^[a-zA-Z]+$', max_length=30, label=_("last name"), error_messages={'invalid': _("Wrong Last Name, use only letters")}) email = forms.EmailField(required=True) remember_me = forms.BooleanField(required=False) class Meta: model = User fields = ['username', 'first_name', 'last_name', 'email', 'password1', 'password2'] views.py def loginPage(request): if request.user.is_authenticated: return redirect('index') else: if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') remember_me = request.POST.get('remember_me') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) if not remember_me: request.session.set_expiry(0) return redirect('index') else: messages.info(request, 'Username OR password is incorrect') context = {} return render(request, 'members/login.html', context) login.html <div class="form-group custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input" name="remember_me" id="remember_me"> <label class="custom-control-label" for="remember_me">Remember me</label> <a class="tdu btn-fpswd float-right" href="#">Forgot Password?</a> </div> Of course above code doesn't work. Thank you! -
Factory Boy: how to set conditional SubFactory() attribute depending on params
I got a Customer model which is related to a Company model. I'd like to give my factory the possibility to use a given company (if I need several customer from the same company). I thought to use the inner class Params to achieve that, but I got an issue using LazyAttribute and SubFactory together. Here is my factory: class CustomerFactory(UserFactory): """ To be valid, customer needs to belong to one of these groups: - manager - regular This can be achieved using the `set_group` parameter. Example: manager = CustomerFactory(set_group=manager_group) """ @lazy_attribute def _company(self): if self.use_company: return self.use_company else: return SubFactory('rdt.tests.factories.CompanyFactory') class Meta: model = Customer class Params: use_company = None @post_generation def set_group(self, create, extracted, **kwargs): if extracted: self.groups.add(extracted) I thought to use the factory as: c1 = factories.CustomerFactory(use_company=my_company) c2 = factories.CustomerFactory() I got ValueError. It seems I can't get the parameter value 'use_company' in the factory. Anyway my factory throws a ValueError. -
DRF-extensions queryset use select_related,show different sql result,
I try to use DRF-extensions for the caches. but same queryset ,Will produce different sql query time, my code: view.py queryset = Users.objects.select_related('location', 'status', 'department', 'position', 'payper') no DRF-extensions# # # # # # # # # # # # # # # # # # # # def list(self, request, *args, **kwargs): result: use DRF-extensions# # # # # # # # # # # # # # # # # # # @cache_response(timeout=60 * 60, key_func=StaffListKeyConstructor()) def list(self, request, *args, **kwargs): result: is this a bug ?How can i fix it, thanks -
Return nested JSON from Models with relations in Django
models.py (simplified) class Author(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name def get_books(self): return Book.objects.filter(author=self.pk) class Book(models.Model): name = models.CharField(max_length=255) pages = models.IntegerField() author = models.ForeignKey(Author, on_delete=models.CASCADE) def __str__(self): return f'{self.name} from {self.author}' class Paragraph(models.Model): name = models.CharField(max_length=255) book = models.ForeignKey(Book, on_delete=models.CASCADE) def __str__(self): return f'{self.name} from {self.book}' I want to return all the instances in a json file with this structure: [ { "name": 'Dumas', "books": { "name": "The count of Montecristo", "paragraphs": { "name": "paragraph_name_1", }, { "name": "paragraph_name_2", }, { "name": "The three Musketeers", "paragraphs": { "name": "paragraph_name", }, ] What I tried: serializers.py class AuthorSerializer(serializers.ModelSerializer): books = serializers.CharField(source='get_books', read_only=True) class Meta: model = Author fields = ['name', 'books'] This add the books key but the value is the string representation of the istances of Book (of course), how I make the value being the serialized istances of Book? I have created a BookSerializer. Notes: I know that I can created a nested json by creating a serializer for Paragraph with depth = 2 but this will include fields I don't want (like pages in Book) and the json structure will be totally different.