[英]Django Models making unique ,unique_together
I am a beginner and building Real-Time Chat with Django Web Sockets for my portfolio ,so I have model Thread that contains first_person and second_person , so it is like one to one room .我是一个初学者,正在为我的投资组合使用 Django Web Sockets 构建实时聊天,所以我有包含 first_person 和 second_person 的模型线程,所以它就像一对一的房间。
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
from django.db.models import Q
class ThreadManager(models.Manager):
def by_user(self, **kwargs):
user = kwargs.get('user')
lookup = Q(first_person=user) | Q(second_person=user)
qs = self.get_queryset().filter(lookup).distinct()
return qs
class Thread(models.Model):
first_person = models.ForeignKey(User,on_delete = models.CASCADE,related_name='first_person')
second_person = models.ForeignKey(User,on_delete = models.CASCADE,related_name='second_person')
objects = ThreadManager()
updated = models.DateTimeField(auto_now=True)
timestamp = models.DateTimeField(auto_now_add=True)
class Meta:
unique_together = ('first_person', 'second_person')
My problem is that , i want to make this Thread model unique .我的问题是,我想让这个 Thread 模型独一无二。 I used unique_together, as you can see in Thread model ,but it only works for one way .For example , if i enter first_person : Alex and second_person : Sam ,it saves .
正如您在线程模型中看到的那样,我使用了 unique_together,但它仅适用于一种方式。例如,如果我输入 first_person:Alex 和 second_person:Sam,它会保存。 But in vice versa , it also saves,if i change the places of people ,like : first_person :Sam and second_person : Alex .
但反之亦然,如果我改变人们的位置,它也会保存,比如:first_person:Sam 和 second_person:Alex。
I also tried this code in my admin.py:我还在我的 admin.py 中尝试了这段代码:
class ThreadForm(forms.ModelForm):
def clean(self):
super(ThreadForm, self).clean()
first_person = self.cleaned_data.get('first_person')
second_person = self.cleaned_data.get('second_person')
lookup1 = Q(first_person=first_person) & Q(second_person=second_person)
lookup2 = Q(first_person=second_person) & Q(second_person=first_person)
lookup = Q(lookup1 | lookup2)
qs = Thread.objects.filter(lookup)
if qs.exists():
raise ValidationError(f'Thread between {first_person} and {second_person} already exists.')
but it did not work.I have read that i need to change create function in the Thread manager , but i did not understand how ?但它没有用。我读过我需要在线程管理器中更改创建函数,但我不明白怎么做?
Is there any solutions for that.有没有解决方案。
What if you try something like the following?如果您尝试以下方法怎么办?
class Thread(models.Model):
# More code here
class Meta
constraints = [
UniqueConstraint(
Lower('first_person'),
Lower('second_person'),
name='first_second_name_unique',
),
UniqueConstraint(
Lower('second_person'),
Lower('first_person'),
name='second_first_name_unique',
),
]
Hope you solve the problem.希望你能解决问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.