How to retrieve an object with generic relation (ContentType) in Django

1.5k Views Asked by At

I used ContentType in my django 3.1 project to implement a wishlist.

Here is my models.py:

# Users.models.py
class WishListItem(models.Model):
    owner = models.ForeignKey(User, on_delete=models.CASCADE)
    
    title = models.CharField(max_length=50, null=True, blank=True)
    count = models.IntegerField(null=True, blank=True)
    price = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True)
    
    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id')

I declared the genericRelation in other models (that are from other apps).

For example:

another_app.models.py:

# Support.models.py
class Training_Lists(models.Model):

    title = models.CharField(max_length=50, unique=True)
    cover = models.ImageField(upload_to='photos/support/tranings/', null=True, blank=True)
    is_published = models.BooleanField(default=True)
    slug = models.SlugField(null=False, unique=True)
    price = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True)
    
    tags = GenericRelation(WishListItem, related_query_name='training', null=True, blank=True)

In my scenario, I want to retrieve a training object in order to get it's price.

Based on Django docs for ContentType.get_object_for_this_type(**kwargs), I should retrieve the model type which I am looking for, then get the object with get_object_for_this_type. In the docs, it says:

from django.contrib.contenttypes.models import ContentType
user_type = ContentType.objects.get(app_label='auth', model='user')  # <= here is my question
user_type
<ContentType: user>

user_type.get_object_for_this_type(username='Guido')
<User: Guido>

Here is my question: what are app_lable and model parameters?

In Users.views.py I want to retrieve the price of an Training_Lists object which is added to wishlist as a WishListItem object.

1

There are 1 best solutions below

0
Shubham Khandare On
from django.contrib.contenttypes.models import ContentType
user_type = ContentType.objects.get_for_model(User)  # <= here is your answer
user_type
<ContentType: user>

user_type.get_object_for_this_type(username='Guido')
<User: Guido>

Refer: ContentType get_for_model