![](/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.