Last active
April 26, 2022 13:24
-
-
Save jourdanrodrigues/96e18853b588e5d6270eed5ef14ec196 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.db.models import Q | |
def q_xor(*queries: Q) -> Q: | |
output = Q() | |
for i in range(len(queries)): | |
variation = Q() | |
for j, query in enumerate(queries): | |
variation &= ~query if i == j else query | |
output |= variation | |
return output |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.db.models import Q | |
class Test(models.Model): | |
field_1 = models.ForeignKey(Model1, on_delete=models.CASCADE, null=True) | |
field_2 = models.ForeignKey(Model2, on_delete=models.CASCADE, null=True) | |
class Meta: | |
constraints = [ | |
models.CheckConstraint( | |
check=q_xor(Q(field1=None), Q(field2=None)), | |
name='has_field1_xor_field2', | |
), | |
] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.db import migrations, models | |
from django.db.models import Q | |
class Migration(migrations.Migration): | |
# dependencies = [...] | |
operations = [ | |
# ... | |
migrations.AddConstraint( | |
model_name='test', | |
constraint=models.CheckConstraint( | |
check=Q( | |
Q(Q(('field1', None), _negated=True), ('field2', None)), | |
Q(('field1', None), Q(('field2', None), _negated=True)), | |
_connector='OR', | |
), | |
name='has_field1_xor_field2', | |
), | |
), | |
# ... | |
] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment