简体   繁体   中英

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 .

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 . 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 . But in vice versa , it also saves,if i change the places of people ,like : first_person :Sam and second_person : Alex .

I also tried this code in my 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM