使用Django ManyToManyField检查实例是否存在

时间:2018-08-09 17:12:12

标签: django django-queryset django-orm manytomanyfield

您好!

如何使用<% Set myMail=CreateObject("CDO.Message") myMail.BodyPart.Charset = "UTF-8" myMail.Subject= Your Message Subject myMail.From= "anotheremail@anotherdomain.com" myMail.To=Receiver Email Address myMail.CreateMHTMLBody "Test Email Subject" myMail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusing")=2 myMail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserver")= SMTP_SERVER myMail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserverport")=25 myMail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1 myMail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusername")=SMTP_Email_Username myMail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendpassword")=Smtp_Email_Password myMail.Configuration.Fields.Update myMail.Send set myMail=nothing %>检查数据库中是否已存在类似记录:

ManyToManyField()

在我看来,创建新会议室之前,我想确保没有与参与者完全相同的活动会议室。

以下示例将不起作用,仅是向您展示我的期望

class Room():
     created_by = models.ForeignKey(User)
     allowed_users = models.ManyToMany(User,related_name='rooms_as_guest')
     is_active = models.BooleanField(default=True)

我该如何继续做我想做的事?

2 个答案:

答案 0 :(得分:1)

不能使用ManyToMany字段创建类似的对象,因为在创建表示m2m关系的中间对象之前,该对象必须存在。您将必须执行以下操作:

allowed_users = User.objects.filter(id__in=request.POST.get("ids", [])).order_by('id')

room = None
for r in up.rooms.filter(is_active=True):
    if list(allowed_users) == list(r.allowed_users.all().order_by('id')):
        room = r # get the existing room
        break

if not room:
    room = Room.objects.create(
        created_by = request.user,
        is_active = True
    )
    room.allowed_users.add(*allowed_users)

您必须确保allowed_users与room.allowed_users的顺序相同。

Check the docs了解更多信息

答案 1 :(得分:1)

这是因为allowed_usersManyToMany字段,因此,需要先创建Room,然后再向其中添加用户。

在此处查看官方文档: https://docs.djangoproject.com/en/2.1/topics/db/examples/many_to_many/#many-to-many-relationships

现在另一个问题是,我们需要获得一个拥有相同用户集的现有会议室,这里已经在类似的问题中对此进行了回答:

Django filter where ManyToMany field contains ALL of list

尝试以下方法:

from django.db.models import Count

allowed_users = User.objects.filter(id__in=request.POST.get("ids",[]))
if allowed_users:
    room = Room.objects.filter(allowed_users__in=allowed_users).annotate(num_users=Count('allowed_users')).filter(num_users=len(allowed_users)).first()
    if not room:
        room = Room.objects.create(created_by=request.user, is_active=True)
        room.allowed_users.add(*allowed_users)