Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limit a single record in model for django app?

I want use a model to save the system setting for a django app, So I want to limit the model can only have one record, how to do the limit?

like image 499
zhongshu Avatar asked Jan 21 '10 03:01

zhongshu


2 Answers

Try this:

class MyModel(models.Model):
    onefield = models.CharField('The field', max_length=100)

class MyModelAdmin(admin.ModelAdmin):
  def has_add_permission(self, request):
    # if there's already an entry, do not allow adding
    count = MyModel.objects.all().count()
    if count == 0:
      return True

    return False
like image 139
mpeirwe Avatar answered Sep 19 '22 13:09

mpeirwe


An easy way is to use the setting's name as the primary key in the settings table. There can't be more than one record with the same primary key, so that will allow both Django and the database to guarantee integrity.

like image 36
John Feminella Avatar answered Sep 19 '22 13:09

John Feminella