1

I have the following models:

class District(models.Model):
   pk_district = models.AutoField(primary=True)

class Block(models.Model):
   pk_block = models.AutoField(primary=True)

class Community(models.Model):
   pk_community = models.AutoField(primary=True)

class RelateOne(models.Model):
   pk_object = models.OneToOneField('District or Block or Community')
   name = models.CharField()

class RelateTwo(models.Model):
   pk_object = models.OneToOneField('District or Block or Community')
   name = models.CharField()

I want the RelateOne or RelateTwo model to associate District or Block or Community, and then I can use it like this:

district = District.objects.get(pk=1)
district.relate_one.name
district.relate_two.name

block = Block.objects.get(pk=1)
block.relate_one.name
block.relate_two.name

Block.objects.select_related('relate_one','relate_two')

How should I set up the model correctly?

starryrbs
  • 31
  • 3

1 Answers1

0

You can use GenericForeignKey from django docs: https://docs.djangoproject.com/en/3.2/ref/contrib/contenttypes/

I would specify the key in Block or District to ensure there is only "one" block per generic relation

Make sure to specify related attributes to get the reverse relationship, although in your case you don't need that.

so it would look something like this:

class Community(models.Model):
   pk_community = models.AutoField(primary=True)
   content_type = models.ForeignKey(ContentType, 
                                    on_delete=models.CASCADE)
   object_id = models.CharField(max_length=100)
   content_object = GenericForeignKey("content_type", "object_id")

class RelateOne(models.Model):
   name = models.CharField(primary_key=)

class RelateTwo(models.Model):
   name = models.CharField(primary_key=True)

# to use it would be something like this:
rel1= RelationOne(name="john")
rel2= RelationTwo(name="dave")
com_data={content_object=rel1,**your_other_data}
com=Community(**com_data)
com.save

#then to access relation:
com.content_object.rel_one_or_two_field....
# remember to be careful as these are generic, it's best to let a 
#serializer take care of this.
Octavio del Ser
  • 378
  • 1
  • 10
  • The model and contentType mentioned above are not in the same database, and then throw such an error: `the current database router prevents this relation.` – starryrbs Jun 09 '21 at 01:50