Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to convert {filed: value} to {field: field_type_matched_value} in django?
I need to convert a value of a given filed to the value which can match the field type: for example:convert {'uid': ('1' or 1)} to {'uid': 1}, the uid filed type is IntegerField or SmallIntegerField how to do this more pythonic than the following? def convert_to_filed_type(obj, field, value): field_type = Organization._meta.get_field('f_name').get_internal_type() try: if field_type == ('CharField' or 'TextField'): value = str(value) elif field_type == ('IntegerField' or 'SmallIntegerField'): value = int(field_type) # there may be many other logic path return value except Exception as e: print(e) -
Can web app functionality be added to WordPress?
As a beginner to web development I'm stuck in the age old choice of WordPress vs Django. Its for an educational structural engineering website. For ease I'll add the functionality I'm trying to implement below: A learning management system for the videos and quizzes (wordpress themes?) A blog to bring in traffic (wordpress win with the SEO) Little tools such as a beam designer with sliders etc. So the first two can be done easily in WordPress, but the last one not so much. Can these sort of things be added to a WP site on a different page? I'm not against learning Django and doing it that way, it's just quite a time and effort investment so don't want to go that route if it's not the best way forward in the long term for this project (plan is to do the CS50 web development course). Thanks -
BEST WAY FOR MULTIPLE USERS CUSTOM AUTHENTICATION IN DJANGO REST FRAMEWORK
I am working on a multitenant application using django-tenant-schemas and django rest framework.I have implemented authentication using djangorestframework-simplejwt.I have different types of users of the system and I'm trying to find the best way of authentication, if to store authentication details in different tables or store it in one table and use relationships. I have been having a challenge to authenticate the different users using different models using djangorestframework-simplejwt. I will really appreciate any contribution on how I can implement it using different models -
Django-taggit similar posts based on tags in DetailedView
I was trying to show related post inside my django blog applications DetailView using taggit. But its not working Models.py class Post(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) created_on = models.DateTimeField(auto_now_add=True) tags = TaggableManager() View.py > class PostDetail(generic.DetailView): > model = Post > template_name = 'post_detail.html' > post_related = Post.tags.similar_objects().filter(status=1).order_by('-created_on')[:3] > context = { > 'tag':Post.tags, > 'post_related':post_related, > > } HTML {% for post in post_related %} . . . {% endfor %} When running the above I am receiving an error raise TypeError("Can't call %s with a non-instance manager" % func.__name__) TypeError: Can't call similar_objects with a non-instance manager Could anyone pls help me, Thanks in advance -
Get SlugField of User model into the DeleteView of a other model - Django
I created a DeleteView for a model (Bezoeker) which is related to the User model. Because I am referencing the Bezoeker Model in the DeleteView it cannot find the Slugfield of the user model. I thought specifying it in my get_context_data method would do the job (did this with the rest of my views as well). The error message I am getting is telling me that the slugfield is found but the pk is empty. When I type in the supposed url in the browser it works and it directs my to the appropriate instance based on the Pk. Reverse for 'gast-verwijderen' with keyword arguments '{'slug': '-2', 'pk': ''}' not found. My view: class GastDeleteView(LoginRequiredMixin, DeleteView): model = Bezoeker login_url = 'users:login' redirect_field_name = 'register:gastenlijst' #success_url = reverse_lazy('register:gastenlijst') template_name = 'register/gast-verwijderen.html' def get_context_data(self, *args, **kwargs): context = super().get_context_data(**kwargs) context.update( pk=self.kwargs['pk'], bezoeker=get_object_or_404(Bezoeker, pk=self.kwargs['pk']), slug=self.kwargs['slug'], bedrijf=get_object_or_404(Bedrijf, slug=self.kwargs['slug']) ) return context def get_success_url(self): return reverse_lazy('register:gastenlijst', args=[ {"slug": self.kwargs['slug'], "pk": self.kwargs['pk']} ]) My url: urlpatterns = [ path('<slug>/dashboard/gastenlijst/verwijderen/<pk>/', GastDeleteView.as_view(), name='gast-verwijderen'), ] My template: <a class="btn btn-danger" href="{% url 'register:gast-verwijderen' slug=slug pk=pk %}">X</a> Can someone point me in the right direction to fix this? -
Combine and serialize the iterated QuerySet in Django
I am working on a Food List API. I need to get the serialized version of QuerySets of FoodList Table. To be clear, I have an Eateries Model: class Eateries(models.Model): hotelName = models.CharField(max_length=255) longitude = models.FloatField() distanceDeliverd = models.IntegerField(default=1) Also, a Foodlist Model class FoodList(models.Model): hotelID= models.IntegerField(default=1) category = models.IntegerField(default=1) Now I need to fetch the FoodList objects where hotelID==Eateries.EateryId and serialise to JSON I tried a lot. But couldn't solve the issue. This is what I tried to do. nearby_hotels = Eateries.objects.all() for eatery in nearby_hotels: singleFood = FoodList.objects.filter(pk = eatery.pk) # Here I am getting the data. # But its in different format. As I am new to django, I am stucked here -
How to get unique values to compare two columns of the same table?
Currently, I am working on a Django project using SQLite in which I create a message chatbox and I want to fetch the most recent message of logged in user whether it's sent or received. id receiver_id sender_id message_content created_at 1 1 2 some text 2020-08-11 13:29:47.342944 3 3 2 some text 2020-08-11 13:44:55.499638 4 2 1 some text 2020-08-11 14:20:55.499638 5 1 2 some text 2020-08-12 05:06:05.497500 6 2 5 some text 2020-08-12 10:39:31.234082 7 4 1 some text 2020-08-14 13:25:19.357876 After using below SQL query. SELECT max(created_at), * FROM hireo_messages WHERE receiver_id=2 or sender_id=2 GROUP BY receiver_id, sender_id ORDER BY created_at DESC I got the following result. id receiver_id sender_id message_content created_at 6 2 5 some text 2020-08-12 10:39:31.234082 5 1 2 some text 2020-08-12 05:06:05.497500 4 2 1 some text 2020-08-11 14:20:55.499638 3 3 2 some text 2020-08-11 13:44:55.499638 And as you can see id 5, 4 both chat with each other. So I want to fetch all records except id 4 because the most recent chat between 2 users is in id 5. It same concept as used in the Facebook messenger dashboard. please guide me whether it solve with a query or use any other … -
No = float(request.POST.get('No')) TypeError: float() argument must be a string or a number, not 'NoneType'
def predict_chances(request): if request.POST.get('action') == 'post': # Receive data from client No = float(request.POST.get('No')) X1_transaction_date = float(request.POST.get('X1_transaction_date')) X2_house_age = float(request.POST.get('X2_house_age')) X3_distance_to_nearest_MRT_station = float(request.POST.get('X3_distance_to_nearest_MRT_station')) X4_number_of_convenience_stores = float(request.POST.get('X4_number_of_convenience_stores')) X5_latitude = float(request.POST.get('X5_latitude')) X6_longitude = float(request.POST.get('X6_longitude')) Y_house_price_of_unit_area = float(request.POST.get('Y_house_price_of_unit_area')) # Unpickle model model = pd.read_pickle("Valuation.pickle") # Make prediction result = model.predict([[Y_house_price_of_unit_area, ]]) classification = result[0] PredResults.objects.create(No=No, X1_transaction_date=X1_transaction_date, X2_house_age=X2_house_age, X3_distance_to_nearest_MRT_station=X3_distance_to_nearest_MRT_station, X4_number_of_convenience_stores=X4_number_of_convenience_stores, X5_latitude=X5_latitude, X6_longitude=X6_longitude ) return JsonResponse({'result': classification, 'No': No, 'X1_transaction_date': X1_transaction_date, 'X2_house_age': X2_house_age, 'X3_distance_to_nearest_MRT_station': X3_distance_to_nearest_MRT_station, 'X4_number_of_convenience_stores': X4_number_of_convenience_stores, 'X5_latitude': X5_latitude, 'X6_longitude': X6_longitude}, safe=False) def view_results(request): # Submit prediction and show all data = {"dataset": PredResults.objects.all()} return render(request, "results.html", data) -
Python Django redirect after login not working
I am trying to create a simple django login function. User logs in with their data, then is redirected to homepage '/'. However the redirection part is not working. The user is however logged in after this process. def get_login(request): if request.POST.get("action") == "post": username = request.POST.get("username") password = request.POST.get("password") # Authenticate user user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('/') #issue here else: return JsonResponse({'update': 'ERROR: This account does not exist.'}) return render(request, 'login.html') I have spend a little too much time trying to debug this, i tried rendering a template instead of redirecting, that didnt work either. Throwing a jsonresponse (similar to the else statement) however worked and i have no idea why this worked but redirecting didn't. Any idea? -
Django: Local time representation with class-based views and crispy forms
I am building an auction website with Django. Potentially it could be used by users in differing time zones and so I have decided that all the underlying dates and times (such as datetime values in models) will be in UTC. I'm using class-based views (ListView, DetailView, etc.) and crispy for displays. What's the best strategy for conversion to local time on the page? Should I do it in the view or in the template? -
Django testing fails only on PotgreSQL runs and not SQLite
Recently I've changed db engine from SQLite to PostgreSQL. I have successfully migrated whole db design to PostgreSQL (just simple makemigaretions, migrate). Once I ran tests some have failed for some unknown reason (errors suggest that some objects were not created). Failure doesn't apply to all tests, just selected few. Everything has been working before. I'd start investigating what's going on on test-by-test basis, but some bizarre behavior has appeared. Let's say my test is in class MyTestClass and test is called test_do_something and in MyTestClass there are other tests as well. When I'm running python manage.py test MyTestClass I'm getting info that test_do_something has failed. When I'm running python manage.py test MyTestClass.test_do_something everything passes. On SQLite both ways pass. I'm assuming that setUpTestData() and setUp() methods work same way in SQLite and PostgreSQL. Or they don't? Any clue why such discrepancy might be happening? -
Creating models instance frontend in Django Rest Framework
I have a restaurant review application with DjangoRest backend and Vue.js frontend. For now I have two models: class Restaurant(models.Model): maps = models.CharField(primary_key=True, max_length=140, unique=True) adress = models.CharField(max_length=240) name = models.CharField(max_length=140) class RestaurantReview(models.Model): review_author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) maps = models.ForeignKey(Restaurant, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) So I make a model instance of Restaurant from data fetched with Google Places Autocomplete and then make my RestarantReview instance with one of my API endpoint. But now, frontend, I am facing a dilemna because I have various options to complete my goal: I have two buttons frontend, one to create a Restaurant instance and one to create a RestaurantReview instance. I tried and it worked but it's not userfriendly and I get an error if I create a RestaurantReview instance without creating a Restaurant instance. Trigger a function that create a Restaurant instance as soon as a restaurant is selected in Google Places Autocomplete. I tried and it worked but I have unnecessary Restaurant instance with no reviews linked to them. Trigger two functions, one after the other (CreateRestaurant(), CreateReview()) as soon as the user wants to write a review. But I don't think is very efective to have two API … -
Django fails to process get request properly with a misconfiguration in the project’s main urls.py
I’ve got a website I’m writing using Django which is a very basic, rudimentary CMS. For now the feature I am trying to implement involves when a web user enters their fake 12-digit chuckee cheese membership card number, Django should redact the first 8 digits and present it back to the user. All of this takes place on the main landing page with blog post text content. Here is the urlspatterns variable declared inside my project’s parent urls.py: urlpatterns = [ path('admin/', admin.site.urls), path('', include('redactors.urls')), path('', include('posts.urls')), path('', include('counters.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) With that exact urlspatterns, the result is this. As you can see in that image, when the web user enters their membership card number, on the webpage to the right, the card number (below the green heading elements) renders and is processed as intended (which is at this web address location, http://127.0.0.1:8000/?ccEntry=111111111111. The problem is the landing page (as depicted on the left at http://127.0.0.1:8000/), renders the template with the blog post content missing. With the urls.py as configured above, here is a working mirror of my dev server so you people can test: https://c3dca86aea1e.ngrok.io/?ccEntry=111111111111 One solution would be to swap the order in which path('', include('redactors.urls')), … -
Django Automatically load data in a database table on creation
I want to automatically load predefined data into a database table when python manage.py makemigrations is run For example if I have a model class Test(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=2) value = models.IntegerField(default=0) def __str__(self): return str(self.name) I want this database table to populate itself with following data on creation (when python manage.py makemigrations & python manage.py migrate is run) id|name|value| -------------- 1 | AA | 0 | 2 | AB | 0 | 3 | AC | 0 | 4 | AD | 0 | 5 | AE | 0 | 6 | AF | 0 | 7 | AG | 0 | 8 | AH | 0 | 9 | AI | 0 | 10| AJ | 0 | 11| AK | 0 | . | | | . | | | . | | | xx| ZZ | 0 | -------------- -
Static folder problems on multiple apps project on django
im new on django and i have some problems with the static folder. I created a "static folder" on the project root and inside i put folders for each app. Django admin page is charging correctly But css, js, images and others on my index isn't. how can i avoid have this problems in the future? For your answers, thank you so much settings.py https://i.stack.imgur.com/cZLnz.png I set the "{% load static %} " in my html document and i write the static tag like this example: "" -
TemplateSyntaxError: Variable 'user.profile.photo' is an invalid source
I have problem with accessing by the link. I am using easy-thumbnail framework, and I created simple view for user list to list all existing users. Error message: django.template.exceptions.TemplateSyntaxError: Variable 'user.profile.photo' is an invalid source. Django Traceback throws me to this view. views.py file: @login_required def user_list(request): users = User.objects.filter(is_active=True) return render(request, 'account/user/list.html', {'section': 'people', 'users': users}) urls.py file: path('users/', views.user_list, name='user_list'), template list.html: {% extends "base.html" %} {% load thumbnail %} {% block title %}People{% endblock %} {% block content %} <h1>People</h1> <div id="people-list"> {% for user in users %} <div class="user"> <a href="{{ user.get_absolute_url }}"> <img src="{% thumbnail user.profile.photo 180x180 %}"> </a> <div class="info"> <a href="{{ user.get_absolute_url }}" class="title"> {{ user.get_full_name }} </a> </div> </div> {% endfor %} </div> {% endblock %} sample code from base.html: <li {% if section == "people" %}class="selected"{% endif %}> <a href="{% url "user_list" %}">People</a> </li> Thank you for the helping in advance. -
How can I show sum of a foreign key values in object_list
I have an product list and a seperated quantity table for these products. I want to show product quantities bu I couldn't managed it yet. There is more than one quantitiy cards for each product and I want to show sum of them. Here is my related models: stok=quantity, Urunler=Products (sorry for language) class Urunler(models.Model): urun_adi = models.CharField(max_length=250,blank=True) urun_id = models.CharField(max_length=20,blank=True,null=True) barkod = models.CharField(max_length=60,blank=True,null=True) gtin = models.CharField(max_length=60,blank=True,null=True) varkod = models.CharField(max_length=60,blank=True,null=True) urun_kodu = models.CharField(max_length=60,blank=True,null=True,unique=True) raf_yeri = models.CharField(max_length=15,blank=True,null=True) kdv = models.DecimalField(blank=True,null=True, max_digits=5, decimal_places=0) birim_fiyat = models.DecimalField(blank=True,null=True, max_digits=9, decimal_places=2) fiyatlansin = models.BooleanField(default=False) class Meta: verbose_name = "Ürün" verbose_name_plural = "Ürünler" ordering = ['pk'] def __str__(self): return self.urun_adi biryil = datetime.now()+timedelta(days=365) class StokKart(models.Model): urun = models.ForeignKey(Urunler,on_delete=models.CASCADE, related_name="stoklar") expiration = models.DateTimeField(default=biryil) stok = models.DecimalField(default=0, max_digits=9, decimal_places=0) class Meta: verbose_name = "Stok Kartı" verbose_name_plural = "Stok Kartları" ordering = ['expiration'] def __str__(self): return self.urun my views: class UrunList(LoginRequiredMixin, ListView): model = Urunler paginate_by = 40 ordering = ['-pk'] template_name = "urunler.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) urun_list = Urunler.objects.all() urun_filter = UrunFilter(self.request.GET, queryset=urun_list) context['filter'] = urun_filter return context and my template: {% for object in object_list %} <tr> <td> {{object.urun_kodu}} </td> <td> <a href="{% url 'urun-detay' object.pk %}" title="{{ object.urun_adi }}" style="color:black;">{{object.urun_adi}}</a> </td> <td> {{object.barkod}} … -
How to send an authentication email in django?
How can I use the django email framework that after a user registers, I send him a special link that will confirm his account. I know there are question about how to send emails, but please help me with authentication. -
Django quering models with foreignkey
i am creating a project of customer management, in this i want to query some models which are related with ForeignKey. I have created these models. from django.db import models class Customer(models.Model): name = models.CharField(max_length=250, null=True) phone = models.CharField(max_length=10, null=True) email = models.CharField(max_length=250, null=True) date_created = models.DateTimeField(auto_now_add=True, null=True) # to get name as string on behalf of "Customer Object 1" in DB. def __str__(self): return self.name class Tag(models.Model): name = models.CharField(max_length=250, null=True) def __str__(self): return self.name class Product(models.Model): # To make a dropdown menu to choose category. CATEGORY = ( ('Indoor', 'Indoor'), ('Out Door', 'Out Door'), ) name = models.CharField(max_length=250, null=True) price = models.FloatField(null=True) category = models.CharField(max_length=250, null=True, choices=CATEGORY) description = models.CharField(max_length=250, null=True, blank=True) date_created = models.DateTimeField(auto_now_add=True, null=True) tags = models.ManyToManyField(Tag) def __str__(self): return self.name class Order(models.Model): # To make a dropdown menu to choose status. STATUS = ( ('Pending', 'Pending'), ('Out for Delivery', 'Out for Delivery'), ('Delivered', 'Delivered'), ) customer = models.ForeignKey(Customer, null=True, on_delete=models.SET_NULL) product = models.ForeignKey(Product, null=True, on_delete=models.SET_NULL) date_created = models.DateTimeField(auto_now_add=True, null=True) status = models.CharField(max_length=250, null=True, choices=STATUS) Views.py from django.shortcuts import render from .models import * def home(request): customers = Customer.objects.all() orders = Order.objects.all() total_customers = customers.count() total_orders = orders.count() delivered = orders.filter(status='Delivered').count() pending = orders.filter(status='Pending').count() front_end_stuff = … -
Django multiple delete record
How do i delete multiple record in django? record=GroupAndProduct.objects.getlist(id=idproduct) record.delete() -
django migrations TransactionManagementError
Im using PolymorphicModels from django polymorphic . I want to preserve existing data while changing the database schema. I had my models like: class TenantShareItem(PolymorphicModel): class Module(PolymorphicModel): I want to add a OneToOne field in Module to TenantShareItem class Module: tenant_share_item = models.OneToOneField(TenantShareItem, null=True, blank=True, on_delete=models.CASCADE) Im using this approach since if i inherit from TenantShareItem , i will lose the Polymorphic property of Module and wrinting migrations for the models is hectic since i have lots many models inheriting again from Module. After adding the field , im running migrations like : from __future__ import unicode_literals from django.db import migrations, models import uuid def create_share_items(apps, schema_editor): Module = apps.get_model('els', 'Module') TenantShareItem = apps.get_model('els', 'TenantShareItem') ContentType = apps.get_model('contenttypes', 'ContentType') for module in Module.objects.all(): share_item = TenantShareItem.objects.create(id=module.id) print("share item", share_item) share_item.polymorphic_ctype = ContentType.objects.get_for_model(Module) share_item.__class__ = Module share_item.polymorphic_ctype_id = module.id share_item.save() module.tenant_share_item = share_item module.save() class Migration(migrations.Migration): dependencies = [ ('els', '0002_module_tenant_share_item'), ] operations = [ migrations.RunPython(create_share_items) ] Im trying to add to TenantShareItem table for every existing entry in Module and setting the content type .Im stuck at the following error: django.db.transaction.TransactionManagementError: An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block. How … -
How can I apply a custom field validator to a model only when it is updated?
I have a model with a models.DateTimeField field that applies a custom validator to check the datetime can not be in the past: Model: class MyModel(models.Model) mydate = models.DateTimeField(validators=[no_past]) Validator: def no_past(value): """ Check the date and time are not in the past. """ if not value: return now = timezone.now() now = now.replace(second=0, microsecond=0) value = value.replace(second=0, microsecond=0) if value else None if value < now: raise ValidationError( 'Date / time cannot be in the past.', code='no_past' ) Is there a way I can ensure this validator is only applied to new records created, and not when a record is updated? -
page not found 404 django - Login Page
I am trying to login using username and password, On clicking the login button it should redirect to the homepage.html, But i am getting page not found error 404. please help me out. I have posted urls.py, views.py and html tag related to this question below. Please let me know if you need any more details #urls.py from django.urls import path from . import views from django.contrib.auth import views as auth_view urlpatterns = [ path('', views.login, name='login_page'), path('/login_validation/', views.login_validation, name="login_validation"), #path('login/', auth_view.LoginView.as_view(template_name='templates/login.html'), name='login'), #path('logout/', auth_view.LogoutView.as_view(template_name='templates/logout.html'), name='logout'), ] #views.py from django.shortcuts import render, redirect from django.contrib.auth.models import User, auth from django.contrib import messages def login(request): return render(request, "login.html") def login_validation(request): if request.method=='POST': username=request.POST("username") password=request.POST("password") user=auth.authenticate(username=username, password=password) if user is not None: auth.login(request, user) return render(request, "homepage.html") else: return render(request, "login.html") else: return render(request, "login.html") login.html <div class="col-sm-12 controls"> <center> <a id="btn-login" type ="submit" href="{% url 'login_validation' %}" class="btn btn-success">Login </a></center> </div> -
How to Save a ImageField in a model in Django?
I have a CustomUser Model with following fields class CustomUser(AbstractUser): image = models.ImageField(upload_to='images/',blank=True,null=True) email = models.EmailField(_('email address'), unique=True) fullname = models.CharField(null=True,max_length=40) dob = models.DateField(default=date.today) phonenumber = models.CharField(max_length=10, blank=True) passportnumber = models.CharField(max_length=10, blank=True) I am trying to have a progress bar for the image upload so I have two forms in single page as follows <body> <div class='row'> <div class='col-sm-3'></div> <div class="col-sm-6 "> <h4>Register</h4> <form id="uploadform" method=POST enctype=multipart/form-data action="/upload/"> {% csrf_token %} <input type=file id="media" name=media ;> <input type="submit" onclick='copy_url(document.getElementById("media").files[0].name)'> </form> <div class="progress"> <div id="progress-bar" class="progress-bar" role="progressbar" style="width: 0%;" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100">0%</div> </div> <form id="registerform"method="post" enctype="multipart/form-data"> {% csrf_token %} <!-- <div class="form-group "> <label>Image</label> <input name="image" type="file" value=""> </div> --> <div class="form-group "> <input id="image" name="image" type="hidden" value=""> </div> <div class="form-group "> <label>Email address</label> <input name="email" class="form-control" type="email" value=""> </div> <div class="form-group "> <label>Fullname</label> <input name="fullname" class="form-control" type="text" value=""> </div> <div class="form-group "> <label>Dob</label> <input name="dob" class="form-control" type="date" value=""> </div> <div class="form-group "> <label>Phonenumber</label> <input name="phonenumber" class="form-control" type="text" value=""> </div> <div class="form-group "> <label>Passportnumber</label> <input name="passportnumber" class="form-control" type="text" value=""> </div> <div class="form-group "> <label>Username</label> <input name="username" class="form-control" type="text" value=""> <span class="help-block">Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.</span> </div> <div class="form-group "> <label>Password</label> <input name="password" class="form-control" type="text" value=""> </div> … -
How do I quickly get a weighted random instance of a Django model instance based on a weight field on that model?
I'm using Postgres as the database backend but I don't think that will matter. Also, I'd like to still use sqlite3 as the local development database, so ideally any approach will work for both. By "weighted", I mean that some items in that database table are more likely to appear than others based on a heuristic value ranging from 0 to +inf where 0 is "never going to be picked", 1 is "as equal to be picked as any other instance, and 2 is "twice as likely to be picked than any other instance". I've read other SO posts about pulling random instances of models, but as far as I've seen there are no ways to do this quickly involving weights. My model: Has millions of instances. Has a weight DecimalField which can be updated at any time, even during runtime. Is not referenced anywhere except for using this random selection algorithm (so, for example, it can be deleted and recreated at any time with no problems). What I'm after is a fast way to do this that is faster than the solutions I've tried or an explanation to why one of my solutions that I've tried is the fastest …