Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
asyncio task hangs midway
So i am building a scrapper which takes a bunch of urls, a success function that will run via celery if that url was fetched successfully and if any error occurs just return and collect the bunch of urls that were not successfull and send them to be scheduled again to a celery function. Below is the code. class AsyncRequest: def __init__(self, urls_batch, callback, task_name, method, finish_callback=None, *args, **kwargs): """ :param urls_batch: List of urls to fetch in asycn :param callback: Callback that process a successfull response """ self.tasks = [] self.headers = { "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36" } self.urls_batch = urls_batch self.task_name = task_name self.callback = callback self.finish_callback = finish_callback self.args = args self.kwargs = kwargs self.proxy = kwargs["proxy"] if "proxy" in kwargs.keys() else None self.finish_callback = finish_callback self.successfull_urls = [] self.verify_ssl = kwargs["verify_ssl"] if "verify_ssl" in kwargs.keys() else True async def fetch(self, session, url, time_out=15, retry_limit=3, *args, **kwargs): try: for i in range(retry_limit): try: async with session.request(self.method, url, headers=self.headers, timeout=ClientTimeout(total=None, sock_connect=time_out, sock_read=time_out), verify_ssl=self.verify_ssl, proxy=self.proxy) as response: if response.status in [200, 203]: result = await response.text() self.successfull_urls.append(url) self.callback.delay(result, url=url, *self.args, **self.kwargs) return else: logger.error( "{} ERROR===============================================>".format(self.task_name)) logger.error("status: {}".format(response.status)) except … -
How to replace the DefaultRouter functionality for function based views
I like the way DefaultRouter in DRF lists all the endpoints. However I dislike the use of ViewSets and prefer using function based views. I can't seem to find a way to list all my function based views in api/v1 any easy way. Seems like you can only use DefaultRouter with ViewSets Is there any quick way and neat way to list all endpoints the same way DefaultRouter does with function based views? -
Read-the-Docs Local Instance: Docs are built successfully but cannot be found (404)
I have successfully installed an instance of Read-the-Docs locally and integrated with the public instance of Gitlab. I have successfully imported and built three projects (even a private one after some minor code alterations, though it is not normally supported). One of these projects is the default template project that RTD suggests for testing. I can view the docs in the machine where the RTD instance is installed. However, when I press the green "View Docs" button a 404 status code occurs. Supposedly, the docs should be under /docs/template/en/latest. As you can see there is no docs prefix in the available URLs: My assumption was that the endpoints regarding the docs are updated dynamically and the Django application reloads, yet I have been searching the code and I have not found anything to support this assumption. My question is, if anyone has ever come upon this issue and how / if it was resolved? -
How to store response of a Django filter in a variable which can be used in a Django template?
Below is my custom filter related code: @register.filter(name="get_quantity") def quantity(item, user_id): try: id = int(user_id) order_item = models.OrderItem.objects.filter(item=item,user__id=id) if order_item.exists(): return order_item[0].quantity except: return False Now I want to use the returned value (quantity) of the filter in my template file: template.html: {% if item|get_quantity:user_id == False %} <input class="text-center qty" value="0" style="width:30px; display: none;"></input> {% else %} <input class="text-center qty" value="{{ item|get_quantity:user_id }}" style="width:30px;"></input> {% endif %} So, I want to store the returned value of the get_quantity filter in some variable in the if condition so I can use it in the else part of code instead of calling the custom filter again in order to reduce complexity. Can someone guide me how to achieve this? -
Run django development webserver when machine is rebooted or turned on
Is there any way we can run the development webserver through may be cronjob or some service provided by django or any libraries? I am in need of running it when laptop or EC2 server reboots. I am open to nginx as solution, but the default development server is what I need at the moment. -
DRF Serializer Update Says Reverse Foreign Key Field is Null even though it has data
I am trying to update a model, but the serializer is saying that my reverse foreign key field is null even though it has data (and it returns the data when I run a get request). Models: Match Team Model class MatchTeam(models.Model): captain = models.ForeignKey( User, on_delete=models.CASCADE, related_name='match_teams_captained' ) teammates = models.ManyToManyField( User, blank=True, related_name='match_teammates' ) match = models.ForeignKey( MatchModel, on_delete=models.CASCADE, related_name='teams' ) Match Model class MatchModel(models.Model): TYPES = ( (1, "Ex1"), (2, "Ex2"), (3, "Ex3"), (4, "Ex4"), ) is_available = models.BooleanField() is_started = models.BooleanField() is_finished = models.BooleanField() is_deleted = models.BooleanField() type = models.IntegerField(choices=TYPES) team_size = models. PositiveSmallIntegerField() num_teams = models. PositiveSmallIntegerField() created_at = models.DateTimeField(editable=False) # Foreign Keys host = models.ForeignKey( User, related_name='matches_hosted', on_delete=models.CASCADE, ) winning_team = models.OneToOneField( 'MatchTeam', on_delete=models.CASCADE, null=True, blank=True, related_name='+' ) def save(self, *args, **kwargs): if not self.id: self.created_at = timezone.now() return super(MatchModel, self).save(*args, **kwargs) I'm trying to update the MatchTeam model in my serializer, but when I get my MatchModel by pk, it says that 'teams' is null even though it has data when I check the db or run a get request. view.py def put(self, request, pk, format=None): match = self.get_object(pk) serializer = MatchModelSerializer(match, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) print(serializer.errors) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) … -
JqueyUI autocomplete suggestions showing up outside input field
I have set up an autocomplete form with JqueryUi in a Django project. Autocomplete is working fine. Problem is, suggestions are not displayed under my form but on the right side of the screen. I need the suggestion to appear just under my search field as it should and to display only the 10 first products that matches my search. My HTML: <div class="ui-widget"> <input id="prod" class="form-control mr-sm-2" type="text" name="query" placeholder=""> </div> My AJAX: $(function() { $("#prod").autocomplete({ source: "/finder/search_auto", select: function (event, ui) { AutoCompleteSelectHandler(event, ui) }, minLength: 2, }); });$( "#prod" ).autocomplete({ position: { my : "right top", at: "right bottom" } }); function AutoCompleteSelectHandler(event, ui) { var selectedObj = ui.item; } My views.py: $(function() { $("#prod").autocomplete({ source: "/finder/search_auto", select: function (event, ui) { AutoCompleteSelectHandler(event, ui) }, minLength: 2, }); });$( "#prod" ).autocomplete({ position: { my : "right top", at: "right bottom" } }); function AutoCompleteSelectHandler(event, ui) { var selectedObj = ui.item; } -
Is there a way to convert video with open-cv in django file-field?
I'm working on django project and I met a problem with handling videos. In the project, if user upload an image then server handles it with OpenCV and save it. This is how I did. _, out_img = cv2.imencode('.jpg', np.asarray(result_image)).tobytes() out_file = ContentFile(out_img) out_path = '/path/to/save' filemodel.file_field.save(out_path, out_file) filemodel.save() I did try with video, but it wasn't easy. Is there anyone who did the same process? Thanks. -
Deploy Django App serverless on GCP cloud functions
I have a Django webapp (a forum) which have few screens like login, profile, posts, replies, etc.. A regular deployment on dedicated instances (with scalability, performance in mind) seems to be expensive. I have come across serverless deployment of Django apps on AWS Lambda. Here is one such example on AWS. But I couldn't find anything similar on GCP. Is a similar thing possible using GCP cloud functions (GCF)? In other words, can GCF be used to deploy any of the following: a web app which can serve dynamic pages a microservice with multiple rest endpoints -
Dynamically add new ckeditor on page - Django
I am trying to dynamically add a new CKEditor after clicking the button since I want to use dynamic formset. I successfully added the CKEditor but I am not able to write in it. Once I for example try to make something bold, cause I can click on the button in the new one, the change is done only in the first CKEditor which is not a clone. And I do not know, where could be the problem. Can someone help me or show me how to handle CKEditors in dynamic forms in Django? Here is my Javascript code which I use for adding new CKEditor and updating the values. {% block custom_js %} <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script> <script type="text/javascript"> function updateElementIndex(el, prefix, ndx) { var id_regex = new RegExp('(' + prefix + '-\\d+)'); var replacement = prefix + '-' + ndx; if ($(el).attr("for")) $(el).attr("for", $(el).attr("for").replace(id_regex, replacement)); if (el.id) el.id = el.id.replace(id_regex, replacement); if (el.name) el.name = el.name.replace(id_regex, replacement); } function cloneMore(selector, prefix) { var newElement = $(selector).clone(true); var total = $('#id_' + prefix + '-TOTAL_FORMS').val(); newElement.find(':input:not([type=button]):not([type=submit]):not([type=reset])').each(function() { var name = $(this).attr('name') if(name) { name = name.replace('-' + (total-1) + '-', '-' + (total) + '-'); var id = 'id_' + name; … -
Login with single role if user have multiple roles? [closed]
A user is assigned multiple roles.Suppose, If the user is a student he will have access to student dashboard and if the user is a teacher he will have his own dashboard. The problem is when the user have both roles and he logins both of the dashboards are loading. I want the user to see only one dashboard when he logins. And he will be able to switch between the roles only after he logins. class A(APIView): def get(self, request): if user.student: //some code class B(APIView): def get(self, request): if user.teacher: //some code -
Session ID getting changed on redirect django & docker
I have a Django and react project. I'm using Nginx and Gunicorn to run the application. To run all these I'm using docker. So in a Django view, I'm setting a session variable and then redirecting to another view after this. So in that redirected view when I'm trying to access the session variable it's not getting fetched. I'm using the default session to store the session in the django_session table. I checked there as well but I'm not sure why it's not able to fetch the session. The wired part is here that in firefox it's working but not in chrome. But in Firefox I'm getting the below error Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://127.0.0.1/api/user/user-info/. (Reason: CORS request did not succeed). The same project is working in my local (without docker) by running the django's runserver command. Below is how my docker-compose.test.yml file looks like version: "3.8" services: db: image: postgres:12.3 ports: - "5432:5432" env_file: - ./env/.env.dev.db volumes: - postgres_data:/var/lib/postgresql/data/ networks: - backend app: build: context: . dockerfile: ./docker/test-env/app-docker/Dockerfile args: - REACT_APP_API_URL=http://127.0.0.1:8000 volumes: - app_static_files:/app/static - favicon:/app/front_end/app-frontend/build/favicon.ico command: > /bin/sh -c "python manage.py migrate && python manage.py collectstatic --no-input && gunicorn … -
Django - Pass two Models into one view, and display both models
I'm trying to pass two models into a create view, where i am trying to get the the primary key from the URL to retrieve the details from a food truck model so it can be displayed in the page, and where a user can write a review about food truck. Also, I'd like a list of the reviews to be displayed on the page. views.py class TruckReviewView(CreateView): model = Review template_name = 'truckReviews/detail.html' fields = ['speedOfService', 'qualityAndTaste', 'valueForMoney', 'comment'] def get_queryset(self): self.pk = self.kwargs['pk'] queryset = super(TruckReviewView, self).get_queryset() return queryset def get_context_data(self, **kwargs): context = super(TruckReviewView, self).get_context_data(**kwargs) context['truck'] = FoodTrucks.objects.get(truckID=get_queryset()) context['reviews'] = Review.objects.get(truckID=get_queryset()) return context urls.py urlpatterns = [ path('', TruckListView.as_view(), name='reviews-home'), path('truck/<int:pk>/', TruckReviewView.as_view(), name='truck-detail'), path('about/', About.as_view(), name='reviews-about'), ] models.py class FoodTrucks(models.Model): truckID = models.IntegerField(primary_key=True, unique=True, null=False) name = models.CharField(max_length=25) category = models.CharField(max_length=20) bio = models.TextField() avatarSRC = models.TextField(default=None) avatarALT = models.CharField(max_length=20, default=None) avatarTitle = models.CharField(max_length=20, default=None) coverPhotoSRC = models.TextField(default=None) coverPhotoALT = models.CharField(max_length=20, default=None) coverPhotoTitle = models.CharField(max_length=20, default=None) website = models.TextField(default=None) facebook = models.CharField(max_length=100, default=None) instagram = models.CharField(max_length=30, default=None) twitter = models.CharField(max_length=15, default=None) class Review(models.Model): reviewID = models.AutoField(primary_key=True, unique=True, serialize=False, null=False) truckID = models.ForeignKey(FoodTrucks, on_delete=models.CASCADE) userID = models.ForeignKey(User, on_delete=models.CASCADE) datePosted = models.DateTimeField(default=timezone.now) speedOfService = models.IntegerField() qualityAndTaste = models.IntegerField() valueForMoney … -
How to search in a JSONField for a key with spaces in Django with Postgres?
Suppose I've a JSONField namely "data" defined in one of my models.py in Django. The Contents of the field is somewhat similar to the following - { "name": "John", "email": "johndoe@foo.bar", "last name": "Doe" } I need to write a queries of the following form - self.objects.filter(data__name="John") How do I write a similar query for the key "last name". I'm not able to proceed since that key has a space. Was thinking of getting the data and filtering it using python, But I think there would be more efficient way to get it done. I've not real control over the data in the JSONField. So, I can't really change the name of the key. -
Django confirm delete modal
I'm trying to have a modal appear when the user clicks the delete button on a task. The modal has a button with the delete_task_view which takes in the pk of the task. I;m trying to find a way to pass it the pk without creating a modal for every task inside the for loop. template.html <div class="content"> <div class="container-fluid"> <div class="row"> <div class="col-lg-6 col-md-12"> <div class="card"> <div class="card-header card-header-success"> Create Task </div> <div class="card-body"> <form enctype="multipart/form-data" method="POST"> {% csrf_token %} {{form|crispy}} <button type="submit" class="btn submit-btn mt-3 mr-2"><i class="fa fa-share"></i> Submit</button> </form> </div> </div> </div> <div class="col-lg-6 col-md-12"> <div class="card"> <div class="card-header card-header-success"> Tasks </div> <div class="card-body"> <table class="table"> <tbody> <th>Task</th> <th>Action</th> {% for task in tasks %} <tr> <td>{{task.task}}</td> <td class="td-actions text-right"> <button type="button" rel="tooltip" title="Edit Task" class="btn btn-white btn-link btn-sm"> <i class="material-icons">edit</i> </button> <button type="submit" rel="tooltip" title="Remove" class="btn btn-white btn-link btn-sm" data-toggle="modal" data-target="#exampleModalCenter"> <i class="material-icons">close</i> </button> </td> </tr> {% endfor %} </tbody> </table> </div> </div> </div> </div> </div> <!-- Modal --> <div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLongTitle">Confirm Action</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> Are you sure you want to … -
Django DRF signal, post_save is not firing
I am having a issue about creating a token. I setup DRF's TokenAuthentication but when I sign up a user signal is not firing. in settings.py INSTALLED_APPS = [ .. 'rest_framework', 'rest_framework.authtoken', .. ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', ] } inside account app, this signals.py from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver from rest_framework.authtoken.models import Token @receiver(post_save, sender=User) def create_auth_token(sender, instance=None, created=False, **kwargs): print("fired") if created: Token.objects.create(user=instance) I can save the new user but for new user can't create a token. print("firing") not running as well. What am I missing here? -
Why is my Django search filter not able to find newly created entries?
My Django search filter is able to filter and display search queries for existing entries in my database flawlessly. But if I create a new entry and then search for that entry, I do not get any result. Here is my view - def listUser(request): searchTerm = '' if 'search' in request.GET: searchTerm = request.GET['search'] obj = Employee.objects.first() obj.refresh_from_db() searchTerm = Employee.objects.filter( Q(organization__orgname__icontains=searchTerm) | Q(team__teamName__icontains=searchTerm) | Q(agile_team__agileTeamName__icontains=searchTerm) | Q(name__icontains=searchTerm) | Q(assoc_id__icontains=searchTerm)) result = {'searchTerm': searchTerm} return render(request, 'scrapeComments/listUser.html', result) else: context = {'listUser': Employee.objects.all()} return render(request, 'scrapeComments/listUser.html', context) Here is my template to display the search query - <table class="table table-borderless"> <tbody> {% for user in searchTerm %} <tr> <td>{{user.name}}</td> <td>{{user.assoc_id}}</td> <td>{{user.organization}}</td> <td>{{user.team}}</td> <td>{{user.agile_team}}</td> </tr> {% endfor %} </tbody> Thanks in advance! -
Docker: Multiple Compositions
I've seen many examples of Docker compose and that makes perfect sense to me, but all bundle their frontend and backend as separate containers on the same composition. In my use case I've developed a backend (in Django) and a frontend (in React) for a particular application. However, I want to be able to allow my backend API to be consumed by other client applications down the road, and thus I'd like to isolate them from one another. Essentially, I envision it looking something like this. I would have a docker-compose file for my backend, which would consist of a PostgreSQL container and a webserver (Apache) container with a volume to my source code. Not going to get into implementation details but because containers in the same composition exist on the same network I can refer to the DB in the source code using the alias in the file. That is one environment with 2 containers. On my frontend and any other future client applications that consume the backend, I would have a webserver (Apache) container to serve the compiled static build of the React source. That of course exists in it's own environement, so my question is like how … -
Django Comment Function creates HTTP 405 Error
I tried to create a commenting function for my Django blog application and comments as such work fine but I can only add them through my admin page. However, I would like users to be able to add comments to blog posts. Comment model in models.py: class Comment(models.Model): post = models.ForeignKey('feed.Post', on_delete=models.CASCADE, related_name='comments') author = models.ForeignKey(User, on_delete=models.CASCADE) content = models.TextField(max_length=500) date_posted = models.DateTimeField(default=timezone.now) def __str__(self): return self.content I tried to add the commenting function with a Class based view in my views.py: class CommentCreateView(CreateView): model = Comment fields = ['content'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) In my urls.py I have added the comment path as such that it uses the same path as the blog post, so the users can add comments on the same page and after the comment is posted they are still on the page of the post. urlpatterns = [ path('', login_required(PostListView.as_view()), name='feed-home'), path('user/<str:username>/', login_required(UserPostListView.as_view()), name='user-feed'), # Blog Post View path('post/<int:pk>/', login_required(PostDetailView.as_view()), name='post-detail'), # (NOT WORKING) Comment View path('post/<int:pk>/', login_required(CommentCreateView.as_view()), name='post-detail'), path('post/new/', login_required(PostCreateView.as_view()), name='post-create'), path('post/<int:pk>/update', login_required(PostUpdateView.as_view()), name='post-update'), path('post/<int:pk>/delete', login_required(PostDeleteView.as_view()), name='post-delete'), path('about/', views.about, name='feed-about'), ] For my other forms such as login, register etc. I have used crispy forms and I thought I could … -
Django - How to get that an object attribute be automatically updated depending on the actual date?
I need that an object attribute be automatically updated past some puntual date and time. I have a class and a method within this class to try to perform this, but the issue here is that I need to call the method (or access a @property) to this be applied. The code is something like this: class Foo(models.Model): status = models.CharField() expiring_time = models.DateTimeField() def is_active(self): date = datetime.datetime.now() if date > self.expiring_time: self.status = "expired" self.save() I found some similar questions but none of them seems to get the point that I'm looking for. I heard about celery to perform scheduled tasks, but as I understood this just be keep calling the method and is not the same that I'm looking for. I would like to know if is there a way to keep this method "always active", or what could be a way to achieve this? -
How to upload images or static files in a django project
Ive tried everything. I cannot upload images in my website. How to do that. It just gives an icon of an image not the image itself. When i write {% load static %} in my html5 file which is running bootstrap css stuff it simply displays that on the webpage. it takes this command as text. Also ive tried to shift the whole iconic folder i downloaded to static directory but py manage.py collectstatic showed 0 files , 130 unmodified.enter image description here -
django Pagination in ListView
How do i create pagination in Django ListView? and i just want that per page have 5 records only this is my views.py def list(request): user_list = StudentsEnrollmentRecord.objects.all() page = request.GET.get('page', 1) paginator = Paginator(user_list, 10) try: users = paginator.page(page) except PageNotAnInteger: users = paginator.page(1) except EmptyPage: users = paginator.page(paginator.num_pages) return render(request, 'Homepage/search_and_page.html', {'users': users}) class ArticleListView(ListView): model = StudentsEnrollmentRecord page = 5 # if pagination is desired template_name = 'Homepage/studentsenrollmentrecord.html' searchable_fields = ["Student_Users", "id", "Section"] user_list = StudentsEnrollmentRecord.objects.all() def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) return(context) and this is my html search_and_page.html <table id="customers"> <tr> <th>Username</th> <th>Firstname</th> <th>Email</th> </tr> {% for article in object_list %} <tr id="myAnchor"> <td class="grpTextBox">{{ article.username }}</td> <td class="grpTextBox">{{ article.Firstname }}</td> <td class="grpTextBox">{{article.Email}}</td> </tr> {% endfor %} </table> in web view -
How to do product sorting when we search for certain product in Django?
views.py:- def search(request): global pro global products if not request.GET.get('price_filter') == '1' or request.GET.get('price_filter') == '2': q = request.GET.get("q") products = Product.objects.filter(active=True, name__icontains=q) categories = Category.objects.filter(active=True) brands = Brand.objects.filter(active=True) context = {"products": products, "categories": categories, "brands": brands, "title": q + " - search"} return render(request, "shop/home.html", context) pro = products if request.GET.get('price_filter') == '1': products = pro.order_by('price') categories = Category.objects.filter(active=True) brands = Brand.objects.filter(active=True) context = {"products": products, "categories": categories, "brands": brands} return render(request, "shop/home.html", context) elif request.GET.get('price_filter') == '2': products = pro.order_by('-price') categories = Category.objects.filter(active=True) brands = Brand.objects.filter(active=True) context = {"products": products, "categories": categories, "brands": brands} return render(request, "shop/home.html", context) In HTML:- <form method='get' action='#' style="margin-top:-20px; margin-left: 8px;"> <input class="btn btn-outline-dark" type="checkbox" value="1" name="price_filter"/>Low to High <input class="btn btn-outline-dark" type="checkbox" value="2" name="price_filter"/>High to Low <button class="btn" type="submit" value="Sort">Sort</button> </form> Using that search we I am able to sort low to high, but when I choose High to Low, it shows certain Error:- Cannot use None as a query value I know this is not the right method to do this, but can please help me out with this, or guide me with the correct way to do sorting. -
with token authentication method applied in django,I am not able to access fucntions with "POST" method
i have applied token authentication to my api in django rest framework in views.py..now when i send a url request in POSTMAN with the 'Authetication: Token dggjgsjgsjgfjggsdgggs' i am not able to access GET methods but not POST or DELETE methods. -
Is there a Django Mock Library that allows filtering of mocked query sets based on foreign keys
Problem Overview Based on the all() method of a Django model manager, filter all models in query set based on 2 fields. (Doable with Q object) Afterwards, for each model from my filtered query, check if said model is a foreign key in another Django model instance. If the model does not act as foreign key, add its information to a dictionary and append said dictionary to a list If the model does act as a foreign key, ignore it and go to the next model Using django-mock-queries, I can easily mock the features needed to accomplish step 1 (The MockSet objects provided by the library allow the use of filtering with Q objects for Django model attributes). However, it seems that I cannot filter for objects in a MockSet for attributes that are also Django objects (i.e. MockModels used to mock said objects) Concrete Example More concretely, I can filter for MockModels in a MockSet based on attributes like so. mock_set = MockSet(MockModel(attribute_1="foo"), MockModel(attribute_1="bar")) foo_set = mock_set.filter(attribute_1="foo") However, the following use of filter will return an empty queryset mock_model = MockModel(attribute_1="bar") mock_set = MockSet(MockModel(model_attribute=mock_model), MockModel(model_attribute=MockModel(attribute_1="bar"))) foo_set = mock_set.filter(model_attribute=mock_model) I've tried using Model Bakery as an alternative library, however the …