1

I have a model which has a boolean field:

class Library(SocialLinksModelMixin):
    """
    Represents book shelves and places where people have / leave books.
    """
    user = models.ForeignKey(...)
    is_main = models.BooleanField(default=False)

User can have multiple Libraries and I would like to allow setting the main one to ease the flow in the app.

What is the easiest way for switching only one Library is_main to True and all others to False (There is always only 1 Library for a user that is main)

I'm thinking about querying for all libraries and updating each and every one. Maybe there is another way to do that functionality?

Hvitis
  • 502
  • 5
  • 14
  • It is a bit odd that this model is named `Library`. This means that each library points to *exactly one* user? Furthermore that the main library is the same for everyone? – Willem Van Onsem Mar 08 '22 at 11:49

1 Answers1

3

If you have the primary key of the Library to set the is_main to True, you can work with:

from django.db.models import Q

Library.objects.filter(user=my_user).update(
    is_main=Q(pk=my_pk)
)

You might also want to enforce at database level that there can only be one Library with is_main=True per user:

from django.conf import settings
from django.db.models import Q

class Library(SocialLinksModelMixin):
    """
    Represents book shelves and places where people have / leave books.
    """
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE
    )
    is_main = models.BooleanField(default=False)
    
    class Meta:
        constraints = [
            models.UniqueConstraint(fields=('user',), condition=Q(is_main=True), name='one_main_per_user')
        ]
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
  • This is super! Combining those 2 things should save me from updating every single user's library 'manually' ? I mean: Updating one library's is_main field to __True__ would set other Libraries' is_main to __False__? – Hvitis Mar 08 '22 at 12:00
  • @Hvitis: yes, for the same user, you can update all of its libraries with a single query. – Willem Van Onsem Mar 08 '22 at 12:03