Niladry Kar
Niladry Kar

Reputation: 1203

How to provide a counter field for every user in django model?

I want to provide a counter field in my Group1 model i.e. whenever a user create a new group1 object it will save the counter as it is...

For example:

If a user create a new group1 object it will save the counter field value as 1, then 2 for another new group1 object and so on. And I want to do this for every user i.e. for every user the counter field value should start from 1.

This is my Group1 model:

class Group1(models.Model):
   counter = models.IntegerField()
   user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,null=True,blank=True)
   group_Name = models.CharField(max_length=32)

Do anyone have any idea about how to perform this?

Upvotes: 0

Views: 181

Answers (1)

Navid Zarepak
Navid Zarepak

Reputation: 4208

You can count the groups that the user has already created and add one to it.

def group_create_view(request):
    user = request.user
    # Get the count for groups that this user has made and add one
    counter = Group1.objects.filter(user=user).count() + 1
    new_group = Group1.objects.create(user=user, counter=counter, group_name='some_name')

Upvotes: 1

Related Questions