简体   繁体   中英

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.

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

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.

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() .

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