简体   繁体   English

如何在 mysql/django 中添加一个仅限一行的表?

[英]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.我正在为一个小项目使用 Django,我想制作一个只有一行的表格,以在其中添加项目的描述。 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. 可以说您的模型是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: 2022 年 3 月更新:

The easiest and best way is using "has_add_permission()" :最简单和最好的方法是使用“has_add_permission()”

"models.py" : “模型.py”

from django.db import models

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

"admin.py" : “管理员.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() .您可以查看有关has_add_permission()的文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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