简体   繁体   English

如果在 Django 中将一个属性设置为 true,如何将字段/模型设置为只读?

[英]How to set fields/model to readonly if one attribute is set to true in Django?

So, I got three classes:所以,我得到了三个类:

class User(...):
    #... other fields
    name = models.CharField()

class Equipment(...):
    #... other fields 
    inUse = models.Boolean(default=False)

class Ticket(...):
    #... Other fields
    user = models.ForeignKey(...)
    equipment = models.ForeignKey(...)
    ended = models.Boolean(default=False)

Now, when I create a new Ticket , the equipment "inUse" attribute changes to True, so I cannot give the same Equipment to more than one User .现在,当我创建一个新的Ticket ,设备的“inUse”属性更改为 True,因此我不能将相同的Equipment给多个User The thing is that when I set the Ticket to "ended" I'll still be able to change it to not "ended".问题是,当我将Ticket设置为“结束”时,我仍然可以将其更改为“未结束”。 I want not to be able to change that once I set the "ended" attribute of the Ticket to True.一旦我将Ticket的“结束”属性设置为 True,我就不想再改变它。

PS: I'm overriding the method save to make changes in the Equipment when setting up a new Ticket or changing it to "ended". PS:在设置新Ticket或将其更改为“结束”时,我将覆盖方法 save 以在Equipment进行更改。

admin.py管理文件

from django.contrib import admin

from .models import Equipamento, TipoEquipamento, Funcionario, Setor, Ticket

# Register your models here.
class EquipamentoAdmin(admin.ModelAdmin):
    list_display = ['codigo', 'categoria', 'descricao', 'ativo', 'emUso']
    search_fields = ['codigo', 'descricao']

class FuncionarioAdmin(admin.ModelAdmin):
    list_display = ['nome', 'setor', 'email']
    search_fields = ['codigo', 'nome']
    

class TicketAdmin(admin.ModelAdmin):
    list_display = ['id', 'get_user_name', 'get_equipment_name', 'dataDevolucao', 'finalizado']
    autocomplete_fields = ['usuario', 'equipamento']
    
    def get_user_name(self, obj):
        return obj.usuario.nome
    
    def get_equipment_name(self, obj):
        return obj.equipamento.descricao

    get_user_name.short_description = 'Funcionario'
    get_equipment_name.short_description = 'Equipamento'

dumb question, after a few minutes I realized I could set a field like "can Change" in the model so that when I change Status the field will be set to false, and I will not be able to change that model anymore.愚蠢的问题,几分钟后我意识到我可以在模型中设置一个像“can Change”这样的字段,这样当我更改Status该字段将设置为 false,并且我将无法再更改该模型。 Daaah, thanks anyways. Daaah,还是谢谢。

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

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