Questions & Answers

Optimise django manytomany relation

I was wondering if there is a way to make this more optimised.

class AppTopic(models.Model):
  topic = models.CharField(max_length=20) # lowercase (cookies)

class UserTopic(models.Model):
  topic = models.CharField(max_length=20) # Any case (cOoKiEs)
  app_topic = models.ForeignKey(AppTopic) # related to (cookies -> lowercase version of cOoKiEs) 

class User(models.Model):
  topics = models.ManyToManyField(UserTopic) # AppTopic stored with any case

The goal is to have all AppTopics be lowercase on the lowest level, but I want to allow users to chose what capitalisation they want. In doing so I still want to keep the relation with it's lowercase version. The topic on the lowest level could be cookies, the user might pick cOoKiEs which should still be related to the orignal cookies.
My current solution works, but requires an entirely new table with almost no use. I will continue using this if there isn't really a smarter way to do it.

2023-01-23 00:55:09
I can't imagine a case where u need many-to-many User: Usertopic relation. can u explain more? isn't that 1:N ? each user can have many custom app topic names.
Answers(1) :

There's nothing in the Django model API that would allow you to manipulate values from the models themselves. If you don't want to change the value in the database or in the model instance, you can change how it displays on the template level using the lower filter in Django template language.

        {% if condition %}
        {% else %}
            <h1>{{AppTopic|??}}</h1> #AppTopic but camelcase. There's no camelcase filter in Django
        {% endif %}

def View(request, condition)

    return render(request, 'template.html', {condition:'condition'})