Explore Courses Blog Tutorials Interview Questions
0 votes
in Web Technology by (19.9k points)

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?

1 Answer

0 votes
by (25.1k points)

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')

Welcome to Intellipaat Community. Get your technical queries answered by top developers!

30.5k questions

32.6k answers


108k users

Browse Categories