3👍
Using generic relations in django is exactly that. A ForeignKey
to ContentType (content_type) and an IntegerField
to denote the instance id (object_id). These are useful if you don’t know which type of content the ForeignKey
is pointing to. Since you know you’re targeting the Address
model you want to use regular ForeignKey(Address)
instead of generic relations.
In response to your comment
Actually its much easier to use ForeignKey
since you don’t need to go through ContentType.
class Address(models.Model):
street=models.CharField(max_length=100)
city=models.CharField(max_length=100)
class Hospital(models.Model):
name=models.CharField(max_length=100)
created=models.DateTimeField()
address=models.ForeignKey(Address, related_name="hospitals")
class Institution(models.Model):
name=models.CharField(max_length=100)
address=models.ForeignKey(Address, related_name="institutions")
>>> instance=Institution.objects.get(id=1)
>>> instance.address.city
>>> address=Address.objects.get(id=1)
>>> address.institutions.all()
>>> address.hospitals.all()
Are your models going to share addresses? i.e. Can a Hospital
and an Institution
and perhaps a UserProfile
all point to the same address instance? Or is it more likely that each will have it’s own address? I am trying to understand why you’ve created a separate class Address
. If it’s to avoid retyping the same fields into each class you could use an abstract model class and subclass it. Or you might be needing a OneToOneField
which is a two way pointer between the two instances.