Difference between setattr and object manipulation in python/django

前端 未结 2 1612
南旧
南旧 2021-01-30 17:24

I have the following model:

class Ticket(models.Model):
    title = models.CharField()
    merged_to = models.ForeignKey(\"self\", related_name=\'merger_ticket\'         


        
2条回答
  •  醉梦人生
    2021-01-30 17:49

    If you know the objects properties before hand you should probably be using the first method. Just assign property values directly.

    The second can be useful when you need to dynamically assign a value to a property. Perhaps a user has the ability to change the values of a number of different attributes and you don't know which one will have a value before hand, you can dynamically add values

    possible_fields = ['title', 'looser_ticket']
    ticket = Ticket.objects.get(pk=1)
    for field in possible_fields:
      if request.GET.get(field):
         setattr(ticket, field, request.GET[field])
    

    The "not working" is probably not dependent on the way you are setting values, are you sure that you saved your changes afterwards??

提交回复
热议问题