Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use ContentType of Django

2025-04-10 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly explains "how to use Django's ContentType". Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to use Django's ContentType.

Contenttypes is a built-in application of Django that tracks the correspondence between all app and model in a project and records it in the ContentType table.

So what is the purpose of this watch? Here is a scenario where when shopping in an online mall, there will be a variety of coupons, such as general coupons, full coupons, or coupons limited to specific categories. In the database, you can associate coupons with lists of items in different categories through foreign keys:

From django.db import models

Class Electrics (models.Model):

"

Id name

1 Hitachi refrigerator

2 Samsung TV

3 Little Swan washing machine

"

Name = models.CharField (max_length=32)

Class Foods (models.Model):

"

Id name

1 bread

2 roast duck

"

Name = models.CharField (max_length=32)

Class Clothes (models.Model):

Name = models.CharField (max_length=32)

Class Coupon (models.Model): # Special relationship table

"

Id name electric_id food_id cloth_id more... # for each additional table, one more field is added to the structure of the relational table.

1 General coupon null null null

2 refrigerator full coupon reduction 2 null null

3 Bread Carnival null 1 null

"

Name = models.CharField (max_length=32)

Electric = models.ForeignKey (to='Electrics', null=True)

Food = models.ForeignKey (to='Foods', null=True)

Cloth = models.ForeignKey (to='Clothes', null=True)

If it is a general coupon, then all ForeignKey is null, if only for certain items, then the corresponding item ForeignKey records the id of the item, and the irrelevant record is null. But this is problematic: in practice, there are many categories of goods, and it is likely to continue to increase, so there will be more and more foreign keys in the coupon table, but only one or more of these foreign key fields will be used for each record.

Contenttypes application

We can solve this problem well by using the special field GenericForeignKey provided in the contenttypes application. Only the following three steps are required:

Define the ForeignKey field in model and associate it to the ContentType table. Usually this field is named "content_type"

The PositiveIntegerField field is defined in model to store the primary key in the associated table. Usually this field is named "object_id"

Define the GenericForeignKey field in model, passing in the names of the above two fields.

To make it easier to query coupons for goods, we can also define reverse relationships through the GenericRelation field in the item category.

Sample code:

From django.db import models

From django.contrib.contenttypes.models import ContentType

From django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation

Class Electrics (models.Model):

Name = models.CharField (max_length=32)

Price = models.IntegerField (default=100)

Coupons = GenericRelation (to='Coupon') # is used for reverse queries and does not generate table fields

Def _ str__ (self):

Return self.name

Class Foods (models.Model):

Name = models.CharField (max_length=32)

Price=models.IntegerField (default=100)

Coupons = GenericRelation (to='Coupon')

Def _ str__ (self):

Return self.name

Class Clothes (models.Model):

Name = models.CharField (max_length=32)

Price = models.IntegerField (default=100)

Coupons = GenericRelation (to='Coupon')

Def _ str__ (self):

Return self.name

Class bed (models.Model):

Name = models.CharField (max_length=32)

Price = models.IntegerField (default=100)

Coupons = GenericRelation (to='Coupon')

Class Coupon (models.Model):

"

Coupon

Id name content_type_id object_id_id

Midea's discount coupon 9 (Electrical Meter electrics) 3

Pig's foot buy one get one free coupon 10 2

Antarctic quilts buy 200 minus 50 coupons 11 1

"

Name = models.CharField (max_length=32)

Content_type = models.ForeignKey (to=ContentType) # step 1

Object_id = models.PositiveIntegerField () # step 2

Content_object = GenericForeignKey ('content_type',' object_id') # step 3

Def _ str__ (self):

Return self.name

Note: ContentType is only used in 1-to-many relationships! And the more table has multiple ForeignKey fields.

At this point, I believe you have a deeper understanding of "how to use Django's ContentType". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report