How to limit the number of entries in django database ? Using the default database (sqlite3)

Viewed 827

How can i specify number of entries in my django database (sqlite3). For example my model is:

from django.db import models

class About(models.Model):
    firstname = models.CharField(max_length=500)
    lastname = models.CharField(max_length=500, blank=True)
    address = models.TextField()
    details = models.TextField()

    class Meta:
        verbose_name_plural = 'About'

    def __str__(self):
        return self.firstname

Now i want to store data of only 2 members in my database. And after adding the data of both users in database from django admin panel, if i try to store data of 3rd member than it should show that database limit is crossed you can't store this data, delete previous data first. Is it possible to limit entries form django models.py .

3 Answers

Write a user defined exception

class DbLimitException(BaseException):
      pass

Override the save method of class About

def save(self,*args,**kwargs):
    total_records = About.objects.count()
    if total_records >= 2:
       raise DbLimitException({"message": "Db limit reached please delete to add more data"})
    else:
       super().save(*args,**kwargs)

You can create a custom ModelAdmin and put your logic there, so if you edit your admin.py for the app that your About model is in to be something like:

from django.contrib import admin
from django.http import HttpResponseRedirect
from django.shortcuts import reverse
from django.contrib import messages

from .models import About

class AboutAdmin(admin.ModelAdmin):
    def add_view(self, request, form_url='', extra_context=None):
        if self.model.objects.count() >= 2:
            self.message_user(request, 'Only two entries can exist at once - please remove others first', messages.ERROR)
            return HttpResponseRedirect(reverse(f'admin:{self.model._meta.app_label}_about_changelist'))
        return super().add_view(request, form_url, extra_context)

admin.site.register(About, AboutAdmin)

That should do the trick...

One thing you can do is this,

view.py

about_count = About.objects.count()
if about_count == 2:
    return render(request, template_name="template.html", context={"error": "You cannot add more entries to the table, you need to delete the previous ones"}

template.html

{% if error %}
   {{error}}
{% endif %}
Related