I started learning Django recently, and can’t find answer for a simple question.
I have 2 tables: Client and Addres.
------------------
CLIENT |
------------------
ID |
NAME |
ADDRES_REF |
------------------
------------------
ADDRES |
------------------
ID |
NAME |
CITY |
COLLECTION |
------------------
The relation between them is: client.addres_ref=addres.collection.
In order to select all addresses of client with ID equal 123 I have to create such query:
select addres.name, addres.city from addres, client where client.addres_ref=addres.collection and client.id=123;
Certainly its posible to create relation many-to-many, but I dont wont create additional table for it and change the structure of tables.
class Addres(models.Model):
address = models.CharField(max_length=150)
city = models.ForeignKey(City)
class Client(models.Model):
addres =models.ManyToMany(Addres)
email =models.EmailField(blank=True)
name =models.CharField(max_length=50)
It is posible to add ForeignKey(Client) in Addres model, but I need reference to Addres from another models too, like User, Employer …
Help me please to create models with relations from above-stated tables.
I think what you need to do is use the content types framework to create generic foreign key in the Addres model.
then client objects will return addresses by using client.addresses or you can query the Addres model like this:
and the Addres model can be linked to other models as well, e.g.