Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python/Django 'WindowsPath' Type Error in Django Rest Framework (DRF)
I keep getting the 'TypeError' below when running a Django project in the virtual environment. What could be the problem? Thanks in advance! File "D:\Studio\Python\REST\elections\env\lib\site-packages\django\db\backends\sqlite3\base.py", line 190, in close if not self.is_in_memory_db(): File "D:\Studio\Python\REST\elections\env\lib\site-packages\django\db\backends\sqlite3\base.py", line 287, in is_in_memory_db return self.creation.is_in_memory_db(self.settings_dict['NAME']) File "D:\Studio\Python\REST\elections\env\lib\site-packages\django\db\backends\sqlite3\creation.py", line 13, in is_in_memory_db return database_name == ':memory:' or 'mode=memory' in database_name TypeError: argument of type 'WindowsPath' is not iterable Here's the settings code for the Databases: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } -
get input to translate a web page django
i'm trying to use multi language for my website by default its language is english , but i 've to add arabic and kurdish(arabic character) to the website ,i want to get input from the user to translate the website to its language for example , in the website we have home - pages - contact map and also some success messages from views.py messages.success(request,_('added')) i need to give privileges' to users who wants translate the website to his/her language , i dont want to use gettext and {% trans %} ! is it possible please ?or isnt there any library for doing that ?!thank you in advance -
Have a constant parameter in all my django URLs
I have a django website that shows data which is seperated in 3 differents databases corresponding to different servers. I have a dropdown list on my website that allow to choose the desired server. What i would like is when a server is chosen, that this choice is keeped all around the website until an other server choice is done. With this choice beeing constant in the URLs like that : website.com/server1/home -> website.com/server1/page-1 -> new server choice -> website.com/server2/page-1 I don't know how to keep this parameter constant without having to pass a variable 'server_name' to every view and every URL of my website. Is there an easier way to do this ? Thank you for your help ! -
Create serializer fields according to the data in Django Rest
I am writing an api for Auth. and I have 2 user types ( Donors , Charity ) when they did registration my data is changing. So that I need to update my fields according to the data. Here is what I did so far. views.py class RegisterView(APIView): def post(self, request): js_data = request.data if 'last_name' in js_data: #fields = ['id', 'email', 'first_name', 'last_name', 'password'] serializer = UserSerializer(data=js_data) serializer.is_valid(raise_exception=True) serializer.save() else: #fields = ['id', 'email', 'first_name', 'postcode', 'password'] serializer = UserSerializer(data=js_data) serializer.is_valid(raise_exception=True) serializer.save() in views.py I tried to define fields from outside serializers.py but I can't send fields as a parameter. serializer = UserSerializer(data=js_data, fields = fields) # gives error. also I tried this one; serializer = UserSerializer(data=js_data, many= True, fields = fields) # gives error So I am trying to create fields dynamically. serializer.py class UserSerializer(serializers.ModelSerializer): class Meta: model = Users fields = [] extra_kwargs = {'password': {'write_only': True} } def create(self, validated_data): if 'last_name' in validated_data: self.Meta.fields = ['id', 'email', 'first_name', 'last_name', 'password'] else: self.Meta.fields = ['id', 'email', 'first_name', 'postcode', 'password'] password = validated_data.pop('password', None) instance = self.Meta.model(**validated_data) if password is not None: instance.set_password(password) instance.save() return instance So in here I tried to change fields in create function. … -
Unable to deploy django project on heroku
I am trying to deploy django project on heroku but I am getting following error. 2021-08-07T10:05:35.789899+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=betabrains.herokuapp.com request_id=2e0f8a7e-ce6f-492b-88d9-81b89a3d7ec0 fwd="223.187.110.102" dyno= connect= service= status=503 bytes= protocol=https 2021-08-07T10:05:36.294818+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=betabrains.herokuapp.com request_id=0bcb0efe-ef5a-4040-9a5e-a5ca56ea9867 fwd="223.187.110.102" dyno= connect= service= status=503 bytes= protocol=https 2021-08-07T10:05:45.842915+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=betabrains.herokuapp.com request_id=fb1e34e7-cc89-4e2f-b7a9-6086b8b8846e fwd="223.187.110.102" dyno= connect= service= status=503 bytes= protocol=https 2021-08-07T10:05:46.803562+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=betabrains.herokuapp.com request_id=bcd75f14-d98a-42c6-9a6f-e43478360d11 fwd="223.187.110.102" dyno= connect= service= status=503 bytes= protocol=https 2021-08-07T10:08:04.166212+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=betabrains.herokuapp.com request_id=93ab6bfb-f8c5-4b5f-9a7a-2eca36b467ed fwd="223.187.110.102" dyno= connect= service= status=503 bytes= protocol=https 2021-08-07T10:08:04.627050+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=betabrains.herokuapp.com request_id=73582b96-2327-4c95-8962-a239c1270075 fwd="223.187.110.102" dyno= connect= service= status=503 bytes= protocol=https my file system is. . ├── Procfile ├── aboutus │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-39.pyc │ │ ├── admin.cpython-39.pyc │ │ ├── apps.cpython-39.pyc │ │ ├── models.cpython-39.pyc │ │ ├── urls.cpython-39.pyc │ │ └── views.cpython-39.pyc │ ├── admin.py │ ├── apps.py │ ├── migrations │ │ ├── __init__.py │ │ └── __pycache__ │ │ └── __init__.cpython-39.pyc │ ├── models.py │ ├── templates │ │ └── aboutus │ │ └── index.html │ ├── tests.py │ ├── urls.py │ └── views.py … -
How to return articles from followed users only?
Right now i am successfully able to return every article without issue. But what i want to do is this: I want to return the articles,only followed by the current authenticated user. How can i do it? models.py class User(AbstractUser,PermissionsMixin): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) email = models.CharField(max_length=255,unique=True) username =models.CharField(max_length=80,unique=True,default='undefinedusername') USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() class Meta: verbose_name = _('user') verbose_name_plural = _('users') 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 UserFollow(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User,on_delete=models.CASCADE,related_name='following') profile = models.ForeignKey(User,on_delete=models.CASCADE,related_name='followers') serializers.py class UserSerializer(DynamicFieldsMixin,serializers.ModelSerializer): userfollowers_set = UserFollowSerializer(source='followers',required=False,many=True) userfollowing_set = UserFollowSerializer(source='following',required=False,many=True) class Meta: model = User fields = ('id','email','username','userfollowing_set','userfollowers_set') views.py class ArticleViewSet(viewsets.ModelViewSet): permission_classes = (IsAuthenticated,) queryset = Article.objects.all().order_by('-timestamp') serializer_class = ArticleSerializer -
django create views use more models
hi everyone I have a doubt with the use of forms and models. I have to create a code that creates records in multiple tables and I don't know how to do it. my goal is to create a page where I can enter all the data and when I save it creates the various tables filled in with the data provided by the user. forms.py from django import forms from .models import Schede, DatiGruppi, Gruppi class CreaSchedaForm(forms.ModelForm): nome_scheda = forms.CharField( required = True, label ='Nome scheda', widget = forms.TextInput( attrs = { 'class': 'form-control', 'placeholder' : 'nome scheda', 'autocomplete' : 'off' } ) ) data_inizio = forms.DateField( label='Data inizio', widget = forms.DateInput( attrs= { 'type': 'date', 'class': 'form-control', 'placeholder' : 'data inizio' } ) ) data_fine = forms.DateField( label='Data fine', widget = forms.DateInput( attrs= { 'type': 'date', 'class': 'form-control', 'placeholder' : 'data fine' } ) ) class Meta: model = Schede fields = ['nome_scheda','data_inizio','data_fine'] class CreaDtGruppoForm(forms.ModelForm): giorni_settimana = forms.ChoiceField( choices = DatiGruppi.giorni_settimana_scelta ) dati_gruppo = forms.ModelChoiceField( queryset = Gruppi.objects.all(), empty_label = "-", required = True ) class Meta: model = DatiGruppi fields = ['giorni_settimana', 'dati_gruppo'] views.py @login_required def creaScheda(request): if request.method == "POST": form = CreaSchedaForm(request.POST) if form.is_valid(): scheda … -
Python/Django 'DEFAULT_PERMISSION_CLASSES' Syntax Error
I'm trying to get my Django project up and running but keep getting the error below when I run the code in the virtual environment. What could be the problem? Thanks! Traceback (most recent call last): File "D:\Studio\Python\REST\elections\manage.py", line 22, in <module> main() File "D:\Studio\Python\REST\elections\manage.py", line 18, in main execute_from_command_line(sys.argv) File "D:\Studio\Python\REST\elections\env\lib\site-packages\django\core\management\__init__.py", line 371, in execute_from_command_line utility.execute() File "D:\Studio\Python\REST\elections\env\lib\site-packages\django\core\management\__init__.py", line 317, in execute settings.INSTALLED_APPS File "D:\Studio\Python\REST\elections\env\lib\site-packages\django\conf\__init__.py", line 56, in __getattr__ self._setup(name) File "D:\Studio\Python\REST\elections\env\lib\site-packages\django\conf\__init__.py", line 43, in _setup self._wrapped = Settings(settings_module) File "D:\Studio\Python\REST\elections\env\lib\site-packages\django\conf\__init__.py", line 106, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) ....... ....... File "D:\Studio\Python\REST\elections\elections\settings.py", line 50 'DEFAULT_PERMISSION_CLASSES': ( ^ SyntaxError: invalid syntax -
How can I display the image to the desired product category? (if there are two separate models (Product and Image))
I can't figure out how to connect two models (product and images) in views and output images in html. At the moment, several images are loaded for a specific project (for example, photos of a 3D model) all this through the admin panel. There are several projects, that is, 3D models, engineering and so on. And now I can't display 1 of those uploaded images on my site for each product (project). That is, either all the images that were uploaded are displayed (both 3d models and books and engineering). Or if you use model.objects.first () displays the very first uploaded image( that is, the same for all projects). My models: class Portfolio (models.Model): modeling='Modeling' books ='Books' engineering='Engineering' category_ch = [ (modeling, 'Modeling'), (books, 'Books'), (engineering, 'Engineering'), ] category = models.CharField('Category',max_length=100,choices=category_ch, default=modeling) name = models.ForeignKey (Teams, related_name='maked', on_delete=models.PROTECT,blank=True) short_discription = models.CharField("Name of the work", max_length=200, blank=True) discription = models.TextField('Discription', blank=True) сustomer = models.CharField('Customer', max_length=100, default='Заказчик') created = models.DateTimeField('Date',auto_now_add=True) class Meta: verbose_name= 'Portfolio' verbose_name_plural = 'Portfolios' def __str__(self): return self.short_discription #def get_absolute_url(self): #return reversed ('shop:product_detail', args=[self.category.slug, self.slug]') class Image(models.Model): image = models.ImageField('Picture of work', upload_to='products/%Y/%m/%d', blank=True) product = models.ForeignKey(Portfolio, default=None, related_name='image', on_delete=models.PROTECT) Views: def portfolio_page(request): portfolio = Portfolio.objects.all() image_work= Image.objects.all() ctx … -
Django Rest Framework: Register pure function-based views with router so it appears under API root
This is my views.py: class ChoicesViewSet(viewsets.ModelViewSet): queryset = SingleChoice.objects.all() serializer_class = SingleChoiceSerializer ... class AssessmentTakersViewSet(viewsets.ModelViewSet): queryset = AssessmentTaker.objects.all() serializer_class = AssessmentTakersSerializer ... @api_view(['POST']) @parser_classes((JSONParser,)) def studio_create_view(request, format=None): """" A view that accept POST request with JSON content and in turn build out the questions and choices. Post with application/json type. """ ... This is my urls.py: urlpatterns = [ # http://localhost:8000/survey/api/studio-create path('api/studio-create', views.studio_create_view, name='studio-create-api'), ] # drf config router = routers.DefaultRouter() router.register('api/choices', views.ChoicesViewSet) router.register('api/assessment-takers', views.AssessmentTakersViewSet) urlpatterns += router.urls This works functionally, and is considered feature-complete, but but because studio-create_view is not registered with the router, the path doesn't show up under the API Root which isn't great documentation wise. In other words, the API root from Django Rest Framework isn't aware of the path, and a GET request to the root would list only: http://localhost:8000/survey/ HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "api/choices": "http://localhost:8000/survey/api/choices/", "api/assessment-takers": "http://localhost:8000/survey/api/assessment-takers/", ... } My question is, outside of viewsets that inherit from ModelViewSet, how do we get the custom views like studio_create_view to be registered with the router that Django Rest Framework provide so it's listed under the API root? One would be inclined to try something like: router.register('api/studio-create', views.studio_create_view, … -
i want to do something on value of a ModelForm before saving in database-django
hiiii,, im trying to do something on value of a ModelForm in django before saving that on database. that "something" is changing the value of datetime field... i want to take jalali datetime from user in form and in template and do something on that(its about changing jalali datetime to gregourian datetime) and save gregourian datetime on database... where should i doing that? in the view or forms? and how?? this is my forms.py (i want do something on datetime field): class NewEvent(ModelForm): class Meta: model = Event fields = ['user','datetime','work'] and this is my view: class CreateEventView(CreateView): form_class = NewEvent template_name = 'app1/new_event.html' i know how to convert jalali to gregourian but i dontknow where should doing that -
Is there any way to clear the session on a browser or tab close in Django as SESSION_EXPIRE_AT_BROWSER_CLOSE = True is not working at all?
When I close a tab or browser and then I run the application again opening the browser again, the previous session remains active. I tried SESSION_EXPIRE_AT_BROWSER_CLOSE = True in settings.py file in the project directory as per the Django documentation. Nothing works. Even the existing solutions in stackoverflow does not work. Is there any way to clear the session on a browser or tab close in Django? -
Bidirectional one-to-may django
I would like to create a bidirectional one-to-many and many-to-one relationship in django like: class User(models.Model): device = dont_know_what_to_write() class Device(models.Model): user = models.ForeignKey( User, on_delete = models.CASCADE ) What should I do? -
Django makemigrations does not create admin databases
I have a django project, this is the installed apps entry in settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'crawler', ] when I run python manage.py migrate everything seems to be fine. But when I try to login into django admin page, It says (1146, "Table 'stock_db.django_session' doesn't exist") It seems to me that migrate is not creating django admin databases, but why? -
in Visual Studio Code, how can i trigger intellisense in an html django template file to get parameters from a .py file under same app?
I'm learning Django and I would like to know if there's a way to trigger intellisense within an html django template file to get a parameter declared in a python class from another under the same app, I'm trying to get the question__text declared in a class in the models.py file. this is by the way the tutorial from the django docs here -
jango filter by latest date in python
I have the following model class CoinsQuotes(models.Model): coinQuotesID = models.AutoField(primary_key=True) coinID = models.ForeignKey(Coins, on_delete=models.CASCADE) coinCurrency= models.CharField(max_length=10) coinPrice = models.DecimalField(decimal_places=8, max_digits=40) coinVolume24h = models.DecimalField(decimal_places=2, max_digits=30) coinPercentageChange1h = models.DecimalField(decimal_places=2, max_digits=20) coinPercentageChange24h = models.DecimalField(decimal_places=2, max_digits=20) coinPercentageChange7D = models.DecimalField(decimal_places=2, max_digits=20) coinPercentageChange30D = models.DecimalField(decimal_places=2, max_digits=20) coinPercentageChange60D = models.DecimalField(decimal_places=2, max_digits=20) coinPercentageChange90D = models.DecimalField(decimal_places=2, max_digits=20) coinPercentageChange180D = models.DecimalField(decimal_places=2, max_digits=20) coinMarketCap = models.DecimalField(decimal_places=2, max_digits=20) coinQuoteLastUpdated = models.DateTimeField('quoteLastUpdated') coinQuotesSnapDate = models.DateTimeField(auto_now_add =True) class CoinsPortfolio(models.Model): coinPortfolioID = models.AutoField(primary_key=True) coinID = models.ForeignKey(Coins, on_delete=models.CASCADE) coinName= models.CharField(max_length=10) coinUSDNotional= models.DecimalField(decimal_places=2, max_digits=30) coinAmount = models.DecimalField(decimal_places=10, max_digits=30) coinBookPrice = models.DecimalField(decimal_places=10, max_digits=40) coinMarketPrice = models.DecimalField(decimal_places=10, max_digits=40) coinBookFees = models.DecimalField(decimal_places=2, max_digits=20) coinBookDate = models.DateTimeField('coinBookDate') coinQuoteLastUpdated = models.DateTimeField('quoteLastUpdated') coinQuotesSnapDate = models.DateTimeField(auto_now_add =True) and I am using the current view to extract the latest quotes for all coins. latest_date = CoinsQuotes.objects.aggregate(latest1 = Max('coinQuotesSnapDate')).['latest1'] pct_chg = CoinsQuotes.objects.all().filter(coinQuotesSnapDate = latest_date) for a reason its returning only one item, while in fact there are 10 coins with the latest time ? additionally is there a way to filter to filter wihin a template of or alternatively should i link those 2 models with many to many relationship ? Many thanks -
How to serve and download zip file stored in media folder in Django?
I am using Django to develop a small API and I want to download files stored in media folder based in id of file stored in a model. this is my API view function def download_trans(request, tran_id, ext): translation = Translation.objects.filter(translator__tran_id=tran_id).first() file_path = os.path.join(translation.file_path.path) if os.path.exists(file_path): with open(file_path, 'rb') as fh: response = HttpResponse(fh.read(), content_type='application/force-download') response['Content-Disposition'] = 'attachment; filename=' + os.path.basename(file_path) return response raise Http404 The download is starting but it gives me file with size of 0 and damaged file because no contents on it. what could be my problem. -
Concurrency Tests in Django
Just started Django last month. I needed help running concurrency tests in django, so what I've done is tried to write code which will prevent issues that arise due to lack of concurrency but what I don't know is how to verify and test the code to see that it meets my expectations. What I want is to send multiple requests at the same time to see if the code works as expected. The target function in views.py def buy_animal(request): context = {} if request.method == 'POST': form = buys_animal(request.POST) if form.is_valid() == True or form.is_valid() == False: #return HttpResponse('asdasd') nm = request.POST['an_name'] b = Animal.objects.filter(an_name = nm) #return HttpResponse("yo ") #nm = request.POST['an_name'] qt = int(request.POST['qty']) if b.count() <= 0: return HttpResponse(str(b.count()) + " Sorry we're out of animals") else: try: with transaction.atomic(): b.select_for_update() b = b[0] #b.an_name = 'asd' #b.save() with transaction.atomic(): Quality.objects.filter( animal = Animal.objects.filter(an_name = 'ringneck')[0] ).select_for_update() c = Quality.objects.filter( animal = Animal.objects.filter(an_name = 'ringneck')[0] )[0] c.rating = 'niece' c.save() except: return HttpResponse('lock in use') if b.qty - qt < 0: return HttpResponse("Sorry we don't have enough animals") else: b.qty = b.qty - qt b.save() a = Buy_animal( an_name = nm, qty = qt, buyer = … -
Using Arabic letters in Django urls causes a 404 error
I want to use Arabic letters in my addresses, there is no problem in local mode, but it causes an error on the server. models.py class Product(models.Model): title = models.CharField(max_length=40, verbose_name='عنوان محصول') slug = models.SlugField(max_length=100,unique=True,allow_unicode=True, verbose_name='آدرس') urls.py urlpatterns = [ path('detail/<str:slug>', ProductDetail.as_view(), name='product_detail') ] views.py class ProductDetail(DetailView): model = Product template_name = 'product_app/product_detail.html' -
how make django sleep
I have a project in which one client register a request and some other clients must answer if they want to work with him or not in real time the problem is that how can i sleep the consumer of him to wait until one of them accepted if i use time.sleep() the whole project will sleep class ConsulationConsumer(WebsocketConsumer): def connet(self): pass def diconnect(self,code_close): pass def receive(self, text_data): text_data_json = json.loads(text_data) consultation = text_data_json['message'] consulator=ConsultationOrder.objects.get(id=consultation).lawyer if(consulator==None): consulator=0 self.send(text_data=json.dumps({ 'message': consulator })) -
menu model design like uber eats menu maker with rules and pricing
I am trying to mimic uber eats menu maker. It has a concepts like modifier, modifier groups, ingredients, preparation time, rules for modifier groups and able to set conditional pricing. I am not quite confident but at least I have implemented modifier, and modifier groups but I stumbled on rules and conditional pricing. By rules I mean to say, modifier groups should be able to allow customers to customize their dishes by allowing them to set constraints for modifier groups to manage exactly what customers can select. This is what rules and conditional pricing looks like This is how I have done so far class MenuItemTag(TimestampBase, ShortUUIDBase): name = models.CharField(max_length=255, null=False) class Meta: verbose_name = "Label" verbose_name_plural = "Labels" default_related_name = "tags" def __str__(self): return self.name or "-" class MenuCategory(TimestampBase, ShortUUIDBase): name = models.CharField(max_length=255, null=False) restaurant = models.ForeignKey("restaurants.Restaurant", on_delete=models.CASCADE) class Meta: verbose_name = "Category" verbose_name_plural = "Categories" default_related_name = "category" def __str__(self): return self.name or "-" class MenuItem(TimestampBase, ShortUUIDBase): CLASSIFICATION_CHOICES = ( ('nonveg', 'Non Veg'), ('vegan', 'Vegan'), ('vegetarian', 'Vegetarian'), ) name = models.CharField(max_length=255, null=False) details = models.TextField(null=True, blank=True) # Precision: 9-digits<decimal_place>6-digits list_price = models.DecimalField( max_digits=15, decimal_places=6, null=True, blank=True, validators=[MinValueValidator(Decimal("0.01"))], ) net_price = models.DecimalField( max_digits=15, decimal_places=6, validators=[MinValueValidator(Decimal("0.01"))] ) restaurant = models.ForeignKey( … -
ERROR: Could not install packages due to an EnvironmentError: [Errno 13] Permission denied
Please Help me to install Django on virtual enviroment My terminal throw this error ERROR: Could not install packages due to an EnvironmentError: [Errno 13] Permission denied: '/home/user/lib/python3.8/site-packages/sqlparse' Consider using the --user option or check the permissions. -
serializer.is_valid returns false with an error that the field is required even though I am passing it
I am building a serializer so that if I post using the following command curl -d '{"food": "test", "portion": 12}' http://127.0.0.1:8000/food it will save to the db. However my problem is serializer.is_valid() returns false with an error that the field "food" is required even though I am passing it. I am unable to change the curl command so how can I make it work? Any help is appreciated. views.py serializer = StockSerializer(data=request.data) if serializer.is_valid(): //save else: print(serializer.errors) //{'food': [ErrorDetail(string='This field is required.', code='required')]} serializer.py class FoodSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ["food", "portion"] Log FoodSerializer(data=<QueryDict: {'{"food": "test", "portion": 12}': ['']}>): food = CharField(max_length=8) portion = IntegerField(required=False) -
How to Update field of Django model based on another model with foreign key relation
I have two models Betslip and Bet,I want to update value of Betslip.settled_status to 'Lost', if Bet.settlement_status is 'half_lost' or 'lost', can anyone create a method for it ? class Betslip(models.Model): SETTLED_STATUS_CHOICE = ( ('InGame','InGame'), ('Won','Won'), ('Lost','Lost'), ('Refunded','Refunded') ) settled_status = models.CharField(choices=SETTLED_STATUS_CHOICE,max_length=30) class Bet(models.Model): SETTLEMENT_STATUS_CHOICE = ( ('','select'), ('won','won'), ('lost','lost'), ('refund','Refund'), ('half_won','half_won'), ('half_lost','half_lost'), ) settlement_status = models.CharField(choices=SETTLEMENT_STATUS_CHOICE,max_length=30,) betslip = models.ForeignKey(Betslip,on_delete=models.CASCADE,related_name='bet')``` -
Obtaining unique set of related models
I'm attempting to get a unique set of Employees that are represented within a queryset of jobs. My models are as follows: class Employee(models.Model): name = models.CharField(max_length=100) class Job(models.Model): employee = models.ForeignKey(Employee, on_delete=models.CASCADE, null=True) start_time = models.DateTimeField(null=True, blank=False) end_time = models.DateTimeField(null=True, blank=False) My query is as follows jobs_list = Job.objects.filter( Q(start_time__lte=start) & Q(end_time__gte=end) ) I'd like to develop a query that gets me a unique queryset of Employees that are related to the jobs_list queryset. Thanks!