Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.4k views
in Technique[技术] by (71.8m points)

django - Enforce or test on_delete behavior of all ForeignKey fields using a specific model

Let's say I have a proxy user model as

class UserWithProfile(User):
    profile_description = models.TextField()

    class Meta:
        proxy = True
        ordering = ('first_name', )

I want to make certain that all data which could in the future be associated with a UserWithProfile entry is deleted when this profile is deleted. In other words I want to guarantee the on_delete behavior of all existing and future ForeignKey fields referencing this model.

How would one implement either a test checking this, or raise an error when another on_delete behavior is implemented?

I know it would be possible to make a custom ForeignKey class, which is what I will be probably doing, ...

class UserWithProfileField(models.ForeignKey):
    def __init__(self, *args, **kwargs):
        kwargs.setdefault('to', UserWithProfile)
        kwargs.setdefault('on_delete', models.CASCADE)
        super().__init__(*args, **kwargs)

... however that couldn't stop future users from using the ForeignKey class with a different on_delete behavior.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Instead of setdefault, you can override the on_delete parameter:

class UserWithProfileField(models.ForeignKey):
    def __init__(self, *args, **kwargs):
        kwargs['to'] = UserWithProfile
        kwargs['on_delete'] = models.CASCADE
        super().__init__(*args, **kwargs)

regardless what the user will now use for to=… or on_delete=…, it will use UserWithProfile and CASCADE.

Strictly speaking one can of course still try to alter the attributes of the ForeignKey, but that is more complicated, especially since Django constructs a ForeignObjectRel object to store relation details.

Note that a proxy model [Django-doc] is not used to add exta fields to the model. THis is more to alter the order, etc. and define new/other methods.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...