I use Django 1.11. Here are the models:
class UserPromoCode(models.Model): promo_code = models.ForeignKey(PromoCode, related_name="user_promo_code") class PromoCode(models.Model): code = models.CharField(max_length=20) You need to get this sample in one or two queries to the database:
promocodes = PromoCode.objects.all() for p in promocodes: p.assigned_times = UserPromoCode.objects.filter(user_promo_code=p.code).count() The problem is that the PromoCode.code field is not unique; therefore, I cannot use the link and execute PromoCode.objects.annontate(assigned_times=Count('user_promo_code')) , which will be an analogue of such a sample:
promocodes = PromoCode.objects.all() for p in promocodes: p.assigned_times = p.user_promo_code.count() I PromoCode.objects.annontate(assigned_times=Count(???)) it should be something like PromoCode.objects.annontate(assigned_times=Count(???)) .