开发者

How to restrict models foreign keys to foreign objects having the same property

开发者 https://www.devze.com 2022-12-13 14:24 出处:网络
Here is my example : We have printers. We can define page formats that are linked to a specific printer then we define workflo开发者_Python百科ws that select a starting format (first page added to th

Here is my example :

We have printers. We can define page formats that are linked to a specific printer then we define workflo开发者_Python百科ws that select a starting format (first page added to the printing job), a body format and an end format (last page added to the printing job).

Start and End are not required (null and blank = True)

I want to be sure that start, body and end will be formats of the same printer.

class Printer(models.Model):
    name = models.CharField(max_length = 20)

class Format(models.Model):
    name = models.CharField(max_length = 20)
    format = models.TextField()
    printer = models.ForeignKey(Printer)

class Workflow(models.Model):
    name = models.CharField(max_length = 20)
    startfmt = models.ForeignKey(Format, related_name = 'start_workflow', null = True, blank = True)
    bodyfmt  = models.ForeignKey(Format, related_name = 'start_workflow')
    endfmt   = models.ForeignKey(Format, related_name = 'start_workflow', null = True, blank = True)

So I need this model to validate that startfmt, bodyfmt and endfmt reference formats that share the same printer... how ?


Your best bet is probably overriding save in the Workflow model:

class Workflow(models.Model):
    # field definitions as you have them

    def save(self, force_insert=False, force_update=False):
        printer = self.bodyfmt.printer
        if self.startfmt and self.startfmt.printer != printer:
            raise ValueError("Startfmt printer does not match")
        if self.endfmt and self.endfmt.printer != printer:
            raise ValueError("Endfmt printer does not match")

        super(Workflow, self).save(force_insert, force_update)
0

精彩评论

暂无评论...
验证码 换一张
取 消