Joseph Groot Kormelink
Joseph Groot Kormelink

Reputation: 289

Django related manager of abstract class

I want to iterate over all my ConnectorModels instances.

class ClientModel(models.Model):
    account = models.ForeignKey(Account, on_delete=models.CASCADE)

class ConnectorModel(models.Model):
    client = models.ForeignKey(ClientModel, on_delete=models.CASCADE)
    class Meta:
        abstract = True

class TelegramModel(ConnectorModel):
    phone = models.CharField(max_length=20)

class URLModel(ConnectorModel):
    phone = models.UR(max_length=20)

When I now get an instantiated version of my ClientModel, I expected to get a connectermodel_set attribute, however I got a TelegramModel_set and an URLModel_set.

How do I get connectormodel_set?

EDIT:

connectormodel_set should return the union of all related telegram and url models

Upvotes: 0

Views: 270

Answers (2)

seuling
seuling

Reputation: 2956

It's because your ConnectorModel is abstract model, not real one. It's only for make other models - TelegramModel and URLModel for your situation.

If you want to call ConnectorModel, please remove abstract from ConnectorModel. And just make other abstract model for others, or just make telegram and url fields to connectormodel. like below.

class ClientModel(models.Model):
    account = models.ForeignKey(Account, on_delete=models.CASCADE)

class ConnectorModel(models.Model):
    client = models.ForeignKey(ClientModel, on_delete=models.CASCADE)
    telegram_phone = models.CharField(max_length=20)
    url_phone = models.CharField(max_length=20)
    # remove abstract
    # class Meta:
    #   abstract = True

# add models with client ForeignKey 
class TelegramModel(models.Model):
    client = models.ForeignKey(ClientModel, on_delete=models.CASCADE)
    phone = models.CharField(max_length=20)

class URLModel(models.Model):
    client = models.ForeignKey(ClientModel, on_delete=models.CASCADE)
    phone = models.UR(max_length=20)

Upvotes: 0

Daniel Roseman
Daniel Roseman

Reputation: 599470

You can't have that with an abstract model. A ForeignKey needs to point to an ID in an actual table, and an abstract model does not represent a table.

There are two options for achieving what you want. The first is to use a concrete base model - which has the disadvantage of an extra database join each time to get the extended data. The second is to use generic relations rather than a foreign key.

Upvotes: 1

Related Questions