Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add many to one relationship with model from external application in django

My django project uses django-helpdesk app. This app has Ticket model.

My app got a Client model, which should have one to many relationship with ticket- so I could for example list all tickets concerning specific client.

Normally I would add models.ForeignKey(Client) to Ticket But it's an external app and I don't want to modify it (future update problems etc.).

I wold have no problem with ManyToMany or OneToOne but don't know how to do it with ManyToOne (many tickets from external app to one Client from my app)

like image 303
Lord_JABA Avatar asked Oct 21 '22 10:10

Lord_JABA


1 Answers

Even more hacky solution: You can do the following in the module level code after you Client class:

class Client(models.Model):
    ...

client = models.ForeignKey(Client, related_name='tickets')
client.contribute_to_class(Ticket, name='client')

I haven't fully tested it (I didn't do any actual database migrations), but the correct descriptors (ReverseSingleRelatedObjectDescriptor for Ticket and ForeignRelatedObjectsDescriptor for Client) get added to the class, and South recognizes the new fields. So far it seems to work just like a regular ForeignKey.

EDIT: Actually not even that hacky. This is exactly how Django sets up foreign keys across classes. It just reverses the process by adding the field when the reverse related class is built. It won't raise an error if any of the original fields on either model is shadowed. Just make sure you don't do that, as it could potentially break your code. Other than that, I don't think there should be any issues.

like image 127
knbk Avatar answered Oct 23 '22 09:10

knbk