Daler
Daler

Reputation: 834

Django creating relation one-to-many

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.

Upvotes: 1

Views: 2368

Answers (2)

Ignas Butėnas
Ignas Butėnas

Reputation: 6307

This could be helpfull - One to many. It's an official documentation, so nothing special...

I'm not sure if I understood question correctly, but what if you will define collection field as foreign key to Client? Then you should be able to do something like

address = Address.objects.get(collection=123)

Upvotes: 3

dting
dting

Reputation: 39287

I think what you need to do is use the content types framework to create generic foreign key in the Addres model.

from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic

class Addres(models.Model):
    content_type = models.ForeignKey(ContentType, related_name='addresses')
    object_id = models.IntegerField()
    content_object = generic.GenericForeignKey( )

    address = models.CharField()
    city = models.ForeignKey(City)

class Client(models.Model):
    addresses = generic.GenericRelation( Addres )
    email = models.EmailField()
    name = models.CharField()

then client objects will return addresses by using client.addresses or you can query the Addres model like this:

client = Client.objects.get(pk=123)
addresses = Addres.objects.filter(content_object=client)

and the Addres model can be linked to other models as well, e.g.

class User(models.Model):
     addresses = generic.GenericRelation( Addres )
     name = models.CharField()

Upvotes: 2

Related Questions