Note that there are some explanatory texts on larger screens.

plurals
  1. POTransforming data when saving and reading from database
    primarykey
    data
    text
    <p>Suppose I have this model (not real code):</p> <pre><code>class Message(models.Model): content = models.CharField(...) mentions = models.ManyToManyField(User) </code></pre> <p>content can for instance be: </p> <blockquote> <p>Say hi to @Adam and @Bernard</p> </blockquote> <p>During the Message model save(), "Adam" and "Bernard" are extracted from the text, and their respective user instances added to mentions, so that</p> <pre><code> &gt;&gt;&gt; m = Message.objects.create(content="Say hi to @Adam and @Bernard") &gt;&gt;&gt; m.mentions.all() &gt;&gt;&gt; [User: Adam, User: Bernard] </code></pre> <p>Now, as to my problem:</p> <p>How do I cope with Bernard performing a sex-change and renaming himself Bernarda? I would very much like the content then to read <code>Say hi to @Adam and @Bernarda</code>.</p> <p>Basically, I've tried a strategy of replacing names with ID's when saving (<code>Say hi to @Adam and @Bernard</code> then becomes <code>Say hi to @1 and @2</code>, i.e. their User.pk's). This works fine when saving, and OK-ish when reading. </p> <p>Doing this replacement in the model's save() method works fine, but read and lookup operations are a major problem. I cannot find an easy way of making sure that what is stored in the database (ie <code>Say hi to @1 and @2</code>) 'magically' becomes <code>Say hi to @Adam and @Bernard</code> whenever it is being queried (be that through .filter() and related operations) or its instance being evaluated.</p> <p>I'm unsure whether I'm on the right track here; any pointers or ideas to doing this differently are very welcome!</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload