[Fixed]-Django models ForeinKey to abstact class

1๐Ÿ‘

โœ…

You can use GenericForeignKey, from the docs

from django.db import models
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType

class TaggedItem(models.Model):
    tag = models.SlugField()
    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id')

    def __str__(self):
        return self.tag

And then:

>>> from django.contrib.auth.models import User
>>> guido = User.objects.get(username='Guido')
>>> t = TaggedItem(content_object=guido, tag='bdfl')
>>> t.save()
>>> t.content_object
<User: Guido>

But this solution maybe problematic in the future.
What about simpler solution

  1. Make profession as choice field
  2. Put your mana, strength, etc in UserProfile model
  3. Dependently on choice set proper value

You can overwrite the save method and if user choice Warrior set strength on 20, etc.

๐Ÿ‘คrzych

0๐Ÿ‘

Check this answer in similar case.

Based on this you can define:

class UserProfile(models.Model):
user = models.OneToOneField(
    User, on_delete=models.CASCADE, related_name='profile'
)
profession = models.ForeignKey(WarriorClass)
๐Ÿ‘คGiaMele

Leave a comment