![](/img/trans.png)
[英]Django deleting a model instance with no more related ForeignKey items in another model?
[英]Update a model after deleting a row in another model in Django
我有兩個模型UserProfile
和ChatUser
。 ChatUser.models.py
class ChatUser(models.Model):
chat = models.ForeignKey(ChatRoom,on_delete=models.CASCADE)
user = models.ForeignKey(User,on_delete=models.CASCADE)
UserProfile.models.py
class UserProfile(models.Model):
user = models.OneToOneField(User,on_delete=models.CASCADE)
phone_number = models.IntegerField(default=0)
image = models.ImageField(upload_to='profile_image',blank=True,default='prof1.jpeg')
gender = models.CharField(max_length=10)
joined = JSONField(null=True)
ChatRoom.models
class ChatRoom(models.Model):
eid = models.CharField(max_length=64, unique=True)
name = models.CharField(max_length=100)
location = models.CharField(max_length=50)
vehicle = models.CharField(max_length=50)
brand = models.CharField(max_length=50)
max_limit = models.IntegerField()
joined
UserProfile 是一個數組,包含聊天室 model 的房間 ID。 現在,當我刪除 ChatRoom 行時,它會自動刪除引用 ChatUser object 的外鍵,因為我使用的是on_delete=models.CASCADE
。 但是如何更新joined
的 UserProfile model。 我想從UserProfile.joined
中刪除已刪除 ChatRoom 的 id
@SAI SANTOSH CHIRAG-請解釋一下。 您有一個添加 user_id 和 chatroom_id 的 ChatUser model。 現在,如果我需要找出用戶加入的聊天室列表,我可以簡單地查詢這個 model。 如果我想找出特定聊天室中的用戶總數,那么我仍然可以查詢此表。 為什么我需要在 UserProfile 中跟蹤加入? 我基於 join 跟蹤用戶加入的聊天室 id 的前提。
在任何時候,如果您選擇在任何模型中添加多對多字段,那么這就是我的觀點。 例如,假設您在 UserProfile model 中添加以下內容
chatroom = models.ManytoManyField(Chat)
想象一下,隨着用戶加入的聊天室數量的增加,列表變得越來越大,我覺得這很不方便,因為我會有一個帶有大列表的小滾動條。 這沒有錯,但我只是為了這個目的遠離 M2M 領域,特別是如果我希望我的列表隨着我的應用程序擴展而增長。
我更喜歡您使用的 ChatUser 方法。 是的,我可能有重復的 user_ids 行或重復的 chatroom_ids,但我不介意。 我可以忍受它。 它對我來說仍然有點清潔。 這只是我的看法。 隨意不同意。 最后,我將 ChatUser model 重命名為 ChatRoomUser ...為什么? 僅通過它的名稱,我可以推斷它與兩個實體聊天室和用戶有關。
我已經使用django.db.models.signals
來解決更新部分。
@receiver(post_delete,sender=ChatUser)
def update_profile(sender,instance,**kwargs):
id = instance.chat_id
joined = instance.user.userprofile.joined
if id in joined:
joined.remove(id)
model = profiles.models.UserProfile.objects.filter(user_id=instance.user.id).update(joined=joined)
SDRJ和Willem Van OnSem ,感謝您的建議
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.