Skip to main content
 首页 » 编程设计

python之在运行时向 Django 模型添加属性

2024年08月16日35lyhabc

具体来说,我有 Django 模型对象,我想在运行时向其添加属性。如果这适用于 Django 之外的任何 python 类,那就太好了。

我有以下型号

模型.py

class person(models.Model): 
    # ... 
    firstname=models.TextField(max_length=100) 
    lastname=models.TextField(max_length=100) 
    type=models.TextField(max_length=100) 
    address = models.ForeignKey(address, null=True) 
 
class event(models.Model): 
    date=models.DateTimeField(auto_now=True ) 
    name=models.CharField(max_length=100)      
    attendees = models.ManyToManyField(person) 
 
def main(): 
    p = person() 
    p.fisrtsname="Firsty" 
    p.lastname="Lasty" 
    p.addnewproperty(newtemporaryproperty) 
    p.newtemporaryproperty="This is a new temporary property" 

当我使用

person.newtemporaryproperty=property("") 

尝试向其添加值时出现“无法设置属性错误”。 我可能用错了。

编辑

我想做的是查看模型中的每个人是否都参加了事件。如果他们有,请在他们的名字旁边打一个复选框。这是附加的相关文件

表格.py

class AttendeesTable(tables.Table): 
    firstname = tables.Column() 
    lastname = tables.Column() 
    here = tables.TemplateColumn('<input id="attendee_{{ record.pk }}" {{  
record.here }} type="checkbox" />', 
                             verbose_name="Here?") 
 
    class Meta: 
        attrs = {'id': 'attendancetable', 'width': '100%', 'class': 'table  
table-hover'} 
        template = 'django_tables2/bootstrap.html' 
        row_attrs = { 
            'id': lambda record: str(record.pk), 
 
        } 

View .py

def markattendancepage(request): 
    person.here = "" 
    people= person.objects.all() 
    groups = group.objects.all() 
    eventid= 1 #set to 1 for testing 
    table=None 
    for p in people: 
 
        if event.objects.filter(id=eventid, attendees__pk=p.id).exists(): 
 
            p.here = "checked" 
        else: 
            p.here = "" 
 
        table = app.tables.AttendeesTable(people) 
 
 
    RequestConfig(request, paginate=False).configure(table) 
    return render(request, 'app/user/attendancechecker.html', {'attendeetable':table}) 
 
    pass 

请您参考如下方法:

因为 django 模型实例经常在幕后重新加载,您可能不想在运行时设置属性,因为它们很容易丢失。相反,您可能想要做的是在类定义中拥有一个属性(或方法),例如

class Person(models.Model): 
    first_name=models.CharField(max_length=100) 
    last_name=models.CharField(max_length=100) 
 
    @property 
    def is_in_category(self): 
        # 'calculation' return a boolean 
        return True if something else False 

然后,如果您有任何特定的 Person 实例,您可以检查 is_in_category 属性

for person in Person.objects.all(): 
    if person.is_in_category: 
        # do something 

这也适用于模板......例如,如果你想制作一张人员表格

<table><tr><th>Name</th><th>In category?</th></tr> 
{% for person in people %} 
    <tr> 
      <td>{{ person.first_name }}, {{person.last_name}}</td> 
      <td>{% if person.is_in_category %}Yes{% else %}No{% endif %}</td> 
    </tr> 
{% endfor %} 
</table> 

但是,由于属性仅作为 Python 结构存在,您不能使用基于此属性的 SQL 查询。

# this will not work 
people_in_category = Person.objects.filter(is_in_category=False) 

如果你想执行这样的查询,你需要在模型或相关模型上创建一个字段,或者以其他方式提出一个与属性等效的 SQL 表达式。

编辑:

根据您的模型,您可以执行一个应该做同样事情的查询。您的 event 模型有一个 attendees 字段,这将是您要查找的内容并且是执行此操作的方法,因为看起来您手头有事件 ID 并且访问事件模型。

evnt = event.objects.get(pk=eventid) 
evnt.attendees # people who attended the event 
did_not_attend = people.objects.exclude(id__in=evnt.attendees) 

您可能需要考虑在模型管理器上创建一个方法,该方法对查询进行注解,以获得与该属性给您的效果相同的效果。例如

class PersonManager(models.Manager): 
    def for_event(self, evnt): 
        attended_event = person.objects.filter(id__in=evnt.attendees) 
        qs = self.get_queryset() 
        return qs.annotate(attended=Exists(attended_event)) 

然后如果你用你的人员模型注册这个经理,你可以做

for p in person.objects.for_event(evnt): 
    if p.attended: 
        # they attended the event