Alexa
Alexa

Reputation: 938

DJANGO saving model types in a field as Generic Foreign Keys

I want to create a new model that look something like this:

class Note(models.Model):
   id = models.AutoField(primary_key=True)
   title = ...
   message = 
   entity = *****************

I want the ******* - to be a foreingKey for any model - not object but model. I don't want entity to be multiple objects of the same model - just the model.

So if the note comes from a Post entity should save as Post, if it comes from a Notification the foriengKey should be to Notification.

Is there a way to do this in django or is my only option to just save the entity name as a String value? and filter for the Model name like.

# Get all the notes for POST Model
Note.objects.filter(entity="Post")

Upvotes: 2

Views: 567

Answers (2)

e4c5
e4c5

Reputation: 53774

it sounds like what you are really looking for is 'choices'.

An iterable (e.g., a list or tuple) consisting itself of iterables of exactly two items (e.g. [(A, B), (A, B) ...]) to use as choices for this field. If this is given, the default form widget will be a select box with these choices instead of the standard text field.

now your model becomes

class Note(models.Model):
    POST = "Post"
    COMMENT = "Comment"
    ...
    ENTITY_CHOICES( (POST,POST), (Comment, Comment) ...)

    id = models.AutoField(primary_key=True)
    title = ...
    message = ...
    entity = models.CharField(max_lenth=5, choices=ENTITY_CHOICES)

Now you can run the query in your comment

 Note.objects.filter(entity="Post")

Upvotes: 1

leotrubach
leotrubach

Reputation: 1597

You could use contenttypes app in Django.

class Note(models.Model):
   id = models.AutoField(primary_key=True)
   title = models.CharField(max_length=50)
   content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
   object_id = models.PositiveIntegerField()
   entity = GenericForeignKey('content_type', 'object_id')

You will be able to assign entity model instances, and also perform queries on them (filter(entity=MyModel.objects.get(id=1))

Upvotes: 1

Related Questions