简体   繁体   中英

How to set limit on models in Django

I have a little problem. I want to set the limit for users in my app. For example: The new user after register and login to his account can add only one record. After added if this same user want to add next record, the app will return the alert "You are permited to add only one record". How to solve it?

You need to have a way to remember if the user used their limit or not. I know 2 options here:

  1. Add a bool/int field to the user that remembers if/how many records that user created.

This is the best tutorial I have found so far regarding extending user model with some additional data: https://simpleisbetterthancomplex.com/tutorial/2016/07/22/how-to-extend-django-user-model.html

  1. Alternatively, you could create a foreign key in a forementioned "record" to the user (eg called "creator"). The reverse link from user to the record would give you the records created by this user.

No matter which solution works better for you, you'll need to check the conditions in the creation view and throw an error if the limit would be exceeded (eg PermissionDenied )

You can build a model similar to this that defines the limit per user and validating the inserted data using a classmethod :

class LimitedRecord(models.Model):
    limits = 5
    user = models.ForeignKey(User)
    data = models.CharField(max_length=128)

    @classmethod
    def add_record(cls, user, data):
        if not cls.can_add(user):
            raise Exception('Not Allowed')
        instance = cls.objects.create(user=user, data=data)
        return instance

    @classmethod
    def can_add(cls, user):
        return cls.objects.filter(user=user).count() <= cls.limits:

I separated the login here into two methods, but sure you can combine them in the same unit that adds the record.

Add two fields to your User model:

class User(models.Model):
    n_records_permitted = models.PositiveIntegerField(default=1)
    n_records_added = models.PositiveIntegerField(default=0)

Now either don't display the relevant form(s) for Users that have user.n_records_added >= user.n_records_permitted or include this check in the form's validation.

And of increase both counters as appropriate.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM