我有一個具有布爾欄位的模型:
class Library(SocialLinksModelMixin):
"""
Represents book shelves and places where people have / leave books.
"""
user = models.ForeignKey(...)
is_main = models.BooleanField(default=False)
用戶可以有多個庫,我想允許設定主要庫以簡化應用程式中的流程。
僅將一個庫 is_main 切換為 True 并將所有其他庫切換為 False 的最簡單方法是什么(對于一個主用戶,始終只有 1 個庫)
我正在考慮查詢所有庫并更新每個庫。也許還有另一種方法可以實作該功能?
uj5u.com熱心網友回復:
如果您有將設定為的主鍵,則可以使用:Libraryis_mainTrue
from django.db.models import Q
Library.objects.filter(user=my_user).update(
is_main=Q(pk=my_pk)
)
Library您可能還希望在資料庫級別強制執行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')
]
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/440200.html
標籤:django django模型 django-rest-framework django-2.2
