开发者

many-to-many relation with extra fields - how to circumvent uniqueness

开发者 https://www.devze.com 2023-02-03 07:02 出处:网络
I have the following task. Having three models Project, User and PurchaseOrder. I want to be able to create a membership for a User in a Project. A User can be a member in arbitrary Projects. This can

I have the following task. Having three models Project, User and PurchaseOrder. I want to be able to create a membership for a User in a Project. A User can be a member in arbitrary Projects. This can be solved with a ManyToManyField.

Additionally a membership should reference to a PurchaseOrder, since I want to assign the working hours to specific PurchaseOrders.

I think this could be solved by using a through-table for the ManyToManyField, and defining a ForeignKey to the PurchaseOrder model. Thus I would have for each开发者_如何学Go membership a reference to a PurchaseOrder.

In reality a membership for a project will stay active, whereas after the money is spend for a PurchaseOrder, a new PurchaseOrder has to be assigned to the membership. This would also be easy by just updating the ForeignKey to a new PurchaseOrder.

But now my question:

I want to keep the old Project-membership-PurchaseOrder-Relation (data row in the membership table, for history tracking), set it to disabled and add a new Project-membership-PurchaseOrder-Relation, which would have the same ForeignKey to User and Project, but a different to the PurchaseOrder, and a flag set to enabled.

Is this a valid approach, will this work, will it be possible to circumvent uniqueness (or is there no uniqueness for the ManyToManyField by definition), or do you have a better idea how to do this?


When I read through this I can't figure out why even bother with the Many-to-Many relation for the Member > PurchaseOrder.

I would make it a One-to-Many relation for Member > PurchaseOrder and a Many-to-Many relation Member > Project, as the Membership appears to be the primarykey for it all.

In that way, you don't have to update any keys. Then I would create a fourth Model, having a Many-to-Many relation keeping track of the purchases. Adding the Membership prim. key and the PurchaseOrder prim.key.

0

精彩评论

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