python - how can model: class1 or class2 have relation with class3 but both Simultaneous don't have relation? -
i have 3 classes:
class 1 has 1 many relation class 3;
class 2 has 1 many relation class 3:
class 1 , 2 not related.
how can model database?

option 1
set foreignkey field null if not needed. may validate in clean() method.
class a(models.model):     # ...     pass  class b(models.model):     # ...     pass  class c(models.model):     # ...     fka = models.foreignkey(a, null=true) # null if not needed     fkb = models.foreignkey(b, null=true) # null if not needed     # ...       def clean(self):         # 1 fk allowed         if self.fka , self.fkb:             raise validationerror("relation either or b - not both!")         # 1 fk required         if not self.fka , not self.fkb:             raise validationerror("relation or b required!")   option 2
work model inheritance
class a(models.model):     # ...     pass  class b(models.model):     # ...     pass  class abstractc(models.model):     # ...      class meta:         # ...         abstract = true  class ctoa(abstractc)     # ...     fka = models.foreignkey(a)     # ...  class ctob(abstractc)     # ...     fkb = models.foreignkey(b)     # ...   database migration:
$ python manage.py makemigrations
$ python manage.py migrate
Comments
Post a Comment