Generic many-to-many relationships

后端 未结 3 529
無奈伤痛
無奈伤痛 2020-12-02 06:03

I\'m trying to create a messaging system where a message\'s sender and recipients can be generic entities. This seems fine for the sender, where there is only object to refe

3条回答
  •  情深已故
    2020-12-02 06:43

    You might get around this problem by simplifying your schema to include a single Client table with a flag to indicate what type of client it was, instead of having two separate models.

    from django.db import models
    from django.utils.translation import ugettext_lazy as _
    
    class Client(models.Model):
        PERSON, CORPORATION = range(2)
        CLIENT_TYPES = (
                        (PERSON, _('Person')),
                        (CORPORATION, _('Corporation')),
                       )
        type = models.PositiveIntegerField(choices=CLIENT_TYPES, default=PERSON)
        city = models.CharField(max_length=16)
        first_name = models.CharField(max_length=16, blank=True, null=True)
        last_name = models.CharField(max_length=16, blank=True, null=True)
        corporate_name = models.CharField(max_length=16, blank=True, null=True)
        tax_no = models.PositiveIntegerField(blank=True, null=True)
    
        def save(self, *args, **kwargs):
            """
            Does some validation ensuring that the person specific fields are
            filled in when self.type == self.PERSON, and corporation specific
            fields are filled in when self.type == self.CORPORATION ...
    
            """
            # conditional save logic goes here
            super(Client, self).save(*args, **kwargs)
    

    If you do things this way you might not have to mess around with Generic Foreign Keys at all. As an added convenience you can also write custom managers for the Client model like Client.corporate.all(), Client.person.all(), to return pre-filtered querysets containing only the type of clients that you want.

    This also may not be the best way of solving your problem. I'm just throwing it out there as one potential possibility. I don't know if there's conventional wisdom about smashing together two similar models and using a save override to ensure data integrity. It seems like it could be potentially problematic ... I'll let the community learn me on this one.

提交回复
热议问题