flow
flow

Reputation: 51

Counting model field dynamically?

Is it possible to count a model field dynamically in django. I have tried using override save model but this is not dynamic:

class MyAdminView(admin.ModelAdmin):
   def save_model(self, request, obj, form, change):
       super(MyAdminView, self).save_model(request, obj, form, change)

Models.py

class JobRequest(models.Model):
    User=models.ForeignKey(user, on_delete = model.CASCADE)
    organization=models.CharField(max_length =150)
    email=models.EmailField(max_length =150)
    country= models.CharField(max_length =150)
    state=models.CharField(max_length =150)
    offer=models.BooleanField(default =True)
    active = models.IntegerField(max_length =150)
    present=models.IntegerField(max_length =150)

I am building a site where users apply for job placement . I will want the present field to count the number of times a user submit a job request and the active field to count the number of offers a user has gotten.

Upvotes: 0

Views: 370

Answers (1)

dirkgroten
dirkgroten

Reputation: 20702

What you want shouldn't be a field on the JobRequest model, since it can easily be retrieved from the db. Ideally this should be a property on your User model since it belongs to a user. But you can also make it a property on the JobRequest instances:

@property
def present(self):
    return self.__class__.objects.filter(user=self.user).count()

@property
def active(self):
    return self.__class__.objects.filter(user=self.user, offer=True).count()

Upvotes: 1

Related Questions