Khaled Al-Ansari
Khaled Al-Ansari

Reputation: 3970

How do I add a table limited to only one row in mysql/django?

I'm using Django for a small project and I want to make a table with one row to add the description of the project in it. I only need one row and nothing more since it's one description for the whole site and I don't want the user to be able to add more than one description.

Upvotes: 6

Views: 2746

Answers (4)

Just inherit yout models from SingletonBaseModel

models.py

class SingletonBaseModel(models.Model):
    def save(self, *args, **kwargs):
        if self.has_add_permission():
            log_exception(f'A record already exists in {self.__class__} model')
            raise ValueError(f'A record already exists in {self.__class__} model')
        super().save(*args, **kwargs)

    def has_add_permission(self):
        return not self.pk and self.__class__.objects.exists()

    class Meta:
        abstract = True

Upvotes: 0

Mar, 2022 Update:

The easiest and best way is using "has_add_permission()":

"models.py":

from django.db import models

class MyModel(models.Model):
    name = models.CharField(max_length=50)    

"admin.py":

from django.contrib import admin
from .models import MyModel

@admin.register(MyModel)
class MyModelAdmin(admin.ModelAdmin):
    def has_add_permission(self, request): # Here
        return not MyModel.objects.exists()

You can check the documentation about has_add_permission().

Upvotes: 0

Khaled Al-Ansari
Khaled Al-Ansari

Reputation: 3970

I solved the problem with the following code

Class Aboutus(models.Model):
    ....

    def save(self):
        # count will have all of the objects from the Aboutus model
        count = Aboutus.objects.all().count()
        # this will check if the variable exist so we can update the existing ones
        save_permission = Aboutus.has_add_permission(self)

        # if there's more than two objects it will not save them in the database
        if count < 2:
            super(Aboutus, self).save()
        elif save_permission:
            super(Aboutus, self).save()

    def has_add_permission(self):
        return Aboutus.objects.filter(id=self.id).exists()

Upvotes: 2

Naveen Kumar
Naveen Kumar

Reputation: 187

Yes this can be done. Lets say your model is MyDescModel.

class MyDescModel(models.Model):
    desc = models.CharField('description', max_length=100)

def has_add_permission(self):
    return not MyDescModel.objects.exists()

Now you can call this

MyDescModel.has_add_permission() 

before calling

MyDescModel.save()

Hope this helps.

Upvotes: 2

Related Questions