django ORM - prevent direct setting of model fields
<p>I have a Django class </p>

<pre><code>class Chat(models.Model):
    primary_node = models.ForeignKey('nodes.Node', blank=True, null=True, related_name='chats_at_this_pri_node', on_delete=models.SET_NULL)
    secondary_node = models.ForeignKey('nodes.Node', blank=True, null=True, related_name='chats_at_this_sec_node', on_delete=models.SET_NULL)
</code></pre>

<p>I want to forbid direct assigning of fields, such as</p>

<pre><code>chat.primary_node = some_node
</code></pre>

<p>and instead create a method <code>chat.assign_node(primary, secondary)</code> that updates nodes via Django <code>Chat.update()</code> model method. </p>

<p>The reason is that I want to log all changes to these nodes (count changes and update other model fields with the new count), but dont want myself and other developers to forget that we cannot assign fields directly, as this wouldn't trigger custom <code>assign_node</code> logic. </p>

<p>How Ñan I do that? </p>

<p>This simply disable setting of 'primary_node'</p>

<pre><code>class Chat(models.Model)
    def __setattr__(self, attrname, val):
        if attrname == 'primary_node': #sets only the attribute if it's not primary_node
            print('[!] You cannot assign primary_node like that! Use assign_node() method please.')
        else:
            super(Chat, self).__setattr__(attrname, val) 
</code></pre>

python django