In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly introduces based on the Django ORM, one-to-one, one-to-many, many-to-many example analysis, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let Xiaobian take you to understand.
1.1 first of all, let's look at a small case:
# _ * _ coding:utf-8_*_from django.db import models # Create your models here. Class Colors (models.Model): colors=models.CharField (max_length=10) # Blue def _ _ str__ (self): return self.colors class Ball (models.Model): color=models.OneToOneField ("Colors") # is one-to-one with the color table, the color table is the parent table description=models.CharField (max_length=10) # describes def _ str__ (self): return self.description class Clothes (models.Model): color=models.ForeignKey ("Colors") # and the color table is a foreign key The color table is description=models.CharField (max_length=10) # describing def _ _ str__ (self): return self.description class Child (models.Model): name=models.CharField (max_length=10) # name favor=models.ManyToManyField ('Colors') # and the color table is many-to-many
Let's first distinguish what is one-to-one and many-to-many.
One-to-one: the child table selects a piece of data from the parent table to correspond one to one. If one item is selected from the parent table, there is one less item. The child table can no longer select the selected data in the parent table.
One-to-many: a child table selects an one-to-one correspondence of data from the parent table, but this data of the parent table can also be selected by other child table data
What they have in common is that if you add data to admin, there will be a select box, but you can only select it alone, because you are "one" whether you are one-to-one or one-to-many.
Many-to-many summary:
For example, having multiple children, and a variety of colors,
Each child can like a variety of colors, one color can be liked by multiple children, and there are multiple choices for both directions.
Application scenario
One-to-one: it is generally used to supplement a table, for example, the basic information of the user is a table, but not every user needs to have login permission and does not need to record the user name and password. At this time, the reasonable thing to do is to create a new table to record the login information, and carry on one-to-one association with the user information. You can easily query the parent table information from the child table or reverse query.
Foreign key: there are many application scenarios, for example, each employee belongs to a department, so you can make an one-to-many association between the department field of the employee table and the department table, and you can find out which department an employee belongs to. You can also reverse find out which employees there are in a certain department.
Many-to-many: for example, in many companies, a server may have multiple uses and belong to multiple product lines, then the server and the product line can be made into many-to-many pairs, and many-to-many manytomany fields can be added to table An or from table B, with the same effect.
one-for-one
Check:
# query the parent table and find the color corresponding to the red ball. # write 1:print (models.Ball.objects.get (description= "red ball"). Color.colors) # return red, query the parent table through the child table, write: "child table object. The lowercase of the name of the parent table. The field name of the parent table "; through the Ball table to find that description is" red ball ", find the corresponding colors# writing 2, reverse from the parent table: print (models.Colors.objects.get (ball__description=" red ball "). Colors) # returns red, queries the parent table through the child table, but formally obtains the field directly from the parent object itself, written as:" parent table .objects.get (child table name lowercase _ _ child table field = "xxx"). The effect of the field name of the master table is exactly the same as above. Another form is # the parent table queries the child table and finds the name of the ball corresponding to red. # write the name of the 1:print (models.Colors.objects.get (colors= "red"). Ball.description) # return the red ball, query the child table through the parent table, and write: "parent object." The lowercase of the name of the child table. Subtable field name "; find the description# writing method 2 of Ball with red color, reverse from the child table: print (models.Ball.objects.get (color__colors=" red "). Description) # returns the red ball, queries the child table through the parent table, but formally obtains the field directly from the child table object itself, writing:" child table .objects.get (one-to-one child table field _ _ parent table field = "xxx"). Subtable field "; the effect is exactly the same as above, another form
Increase:
# add a color black, and add a black ball color_obj=models.Colors.objects.create (colors= "black") # first create a color in the parent table and instantiate it to the color table object models.Ball.objects.create (color=color_obj,description= "black ball") # Update the Ball table, the color field is the color table object, and add the description field
Remarks: 3 common ways to add data
# three ways to add data: # write 1:color_obj=models.Colors.objects.create (colors= "black") models.Ball.objects.create (color=color_obj,description= "black ball") # add: color_id=models.Colors.objects.create (colors= "black") .idmodels.Ball.objects.create (color_id=color_id,description= "black ball") # write 2:color_obj=models.Colors.objects.create (colors= "black") ball_obj=models.Ball (color=color_obj Description= "black ball") ball_obj.save () # written 3 (dictionary import): color_obj=models.Colors.objects.create (colors= "black") ball_dic= {'description': "black ball} models.Ball.objects.create (color=color_obj,**ball_dic)
Change:
Color_obj=models.Colors.objects.get (colors= "black") # .get () equals .filter (). First () color_obj.colors= "color_obj.save" color_obj.save () models.Ball.objects.filter (description= "black ball") .update (color=color_obj,description= "gray ball") # update (), delete () is the method of QuerySet
Remarks: common ways to modify data
# Update a piece of data color_obj=models.Colors.objects.get (colors= "black") color_obj.colors= "gray" color_obj.save () # update multiple pieces of data, change the description of all the balls that meet the conditions into a gray ball # write 1:models.Ball.objects.filter (color__colors= "red") .update (description= "gray ball") # write 2updater = {"description": "gray ball"} models.Ball.objects.filter (id__gt=0). Update (* * up_dic)
Delete:
Models.Ball.objects.get (description= "gray ball"). Delete () # object and QuerySet both have methods delete () models.Colors.objects.filter (colors= "gray"). Delete () models.Colors.objects.all (). Delete () # clear a table
One to many (foreign key)
Check:
# Foreign key table joint query: # Foreign key child table query parent table in the same form as one-to-one child table query parent table # find the color in the color table to which the red underpants belong-return: red # write 1:print (models.Clothes.objects.get (description= "little tiger"). Color.colors) # return red, query the parent table through the child table, write: "child table object. The lowercase of the name of the parent table. The field name of the parent table "; through the Clothes table to find that description is" Brother Tiger ", find the corresponding colors# writing 2, reverse from the parent table: print (models.Colors.objects.get (clothes__description=" Tiger Brother "). Colors) # returns red, queries the parent table through the child table, but formally obtains the fields directly from the parent object itself, written as:" parent table .objects.get (child table name lowercase _ _ child table field = "xxx"). The effect of the parent field name is exactly the same as above, and another form # foreign key parent table queries the child table, which is different from the one-to-one form, because the parent table is "many" and cannot pass .get () like one-to-one. Sub-table. How to get the fields of the child table But consistent with many-to-many parent table query child table # find all clothes with red color-return: [,] # write 1:color_obj=models.Colors.objects.get (colors= "red") print (color_obj.clothes_set.all ()) # Note: subtable lowercase _ set, it is actually a QuerySet, you can use update,delete,all Filter et al. # write 2:print (models.Clothes.objects.filter (color=models.Colors.objects.get (colors= "red")) # 2 easy to write (recommended): print (color__colors= "red") # write: filter (subtable foreign key field _ _ parent table field = 'filter condition') # write 3:color_id=models.Colors.objects.get (colors= "red"). Id # through the parent table Get the red idprint (models.Clothes.objects.filter (color_id=color_id)) # filter to get QuerySet Written in: filter (foreign key field of child table _ primary key of parent table = primary key object of parent table)
Note: convert QuerySet to ValuesQuerySet through the .values () method of QuerySet
Print (models.Clothes.objects.filter (color=models.Colors.objects.get (colors= "red"). Values ('color__colors','description')) # gets the description field of the child table and the colors field of the parent table Get the field writing method of the parent table: child table foreign key field name _ _ parent table field name-applicable to values () or filter () # abbreviated form: print (models.Clothes.objects.filter (color__colors= "red"). Values ('color__colors','description')) # returned: [{' description': u'\ u7ea2\ u5185\ u8863, 'color__colors': u'\ u7ea2'}, {' description': u'\ u7ea2\ u5185\ u88e4' 'color__colors': u'\ u7ea2'}] # if you don't add values (), you will return a QuerySet collection like [,] Through values, you can form a list, and each element in the list is a dictionary, and you can convert ValuesQeurySet into a list through list (), and then return it to templates#. You can also convert QuerySet to ValuesListQuerySet through .values _ list (). Return: [(u'\ u7ea2percent, u'\ u7ea2\ u889c\ u5b50'), (u'\ u7ea2percent, u'\ u7ea2\ u889c\ u5b50')] # you get a list of multiple tuples, each of which is the value of the dictionary in ValuesQuerySet, which is often used to dynamically add data from models to the select option in the front-end template. # pass the value from models to the frontend select option through forms.py. You need to restart django before the select option can be updated. When defining form, add the following keyword to ensure dynamic update of select option # forms.pyfrom django import formsfrom test1 import modelsclass ClothesForm (forms.Form): color=forms.IntegerField (required=True,widget=forms.Select (),) def _ _ init__ (self,*args,**kwargs): # define this key field. When using form, the colors table adds new colors. The option in the color field of the front-end ClothesForm automatically updates super (ClothesForm, self). _ _ init__ (* args,**kwargs) self.fields ['color'] .widget.choices = models.Colors.objects.all (). Order_by (' id'). Values_list ('id','colors')
Increase:
# add child table data The form is consistent with one-on-one # add clothes with green color: handsome guy # method 1:models.Clothes.objects.create (color=models.Colors.objects.get (colors= "green"), description= "handsome guy") # method 1 add: models.Clothes.objects.create (color_id=models.Colors.objects.get (colors= "green") .id, description= "handsome guy") # method 2:c_obj=models.Clothes (color=models.Colors.objects.get (colors= "green") Description= "handsome guy") c_obj.save () # method 3: input in dictionary.. Reference one-on-one
Change:
# clothes with red colors Description are all updated as beauty # 1:models.Clothes.objects.filter (color__colors= "red"). Update (description= "beauty") # 2:models.Clothes.objects.filter (color_id=models.Colors.objects.get (colors= "red") .id). Update (description= "beauty") # update (colors= "red") colors_obj.clothes_set.filter (id__gte=1) .update (description= ") "Beauty") # other writing methods refer to one-to-one modification and foreign key query
Delete:
Models.Clothes.objects.get (description= "gray skirt"). Delete () # object and QuerySet both have methods delete () models.Colors.objects.filter (colors= "gray"). Delete ()
Many to many
Check:
Many-to-many child tables query the parent table to find out which colors Xiao Ming likes-return: [,] # is different from a pair of many child tables to query the parent table, because one-to-many query is the "one" of the parent table; many-to-many query is the "many" of the parent table # 1:child_obj=models.Child.objects.get (name= "Xiaoming") # writing: child table object. Many-to-many fields in child tables. Filter condition (all () / filter ()) print (child_obj.favor.all ()) # write 2 Reverse start with the parent table: print (models.Colors.objects.filter (child__name= "Xiaoming")) # parent table object .filter (child table name lowercase _ _ child table field name = "filter condition") # many-to-many mother table query child table to find who likes yellow-return: [,] # is exactly the same as a pair of multi-mother table query child table form, because all found is QuerySet, one-to-many and many-to-many All query subtable "multiple" # writing method 1:color_obj=models.Colors.objects.get (colors= "yellow") print (color_obj.child_set.all ()) # writing method 2:print (models.Child.objects.filter (favor=models.Colors.objects.get (colors= "yellow")) # easy writing (recommended): print (models.Child.objects.filter (favor__colors= "yellow")) # writing: filter (external key field of the subtable) _ _ parent field = 'filter condition') # write 3:color_id=models.Colors.objects.get (colors= "yellow"). Id # get the red idprint (models.Child.objects.filter (favor=color_id)) # filter through the parent table to get QuerySet Written in: filter (child table foreign key field = parent table primary key object), which is slightly different from one-to-many Is a child table foreign key field instead of a foreign key field _ parent table primary key
Add and change (add child table or parent table data with reference to one-to-one increase, many-to-many focus on the corresponding change of the relational table):
# add child table association # add tiger and make him like all colors # write 1:child_obj=models.Child.objects.create (name= "tiger") # if you are an existing user, use .get () colors_obj=models.Colors.objects.all () # to create all color QuerySet objects of the color table child_obj.favor.add (* colors_obj) # add correspondence, associate tiger with all colors, write as sub-table object. Subtable many-to-many fields. Add (* QuerySet object) # write 2:child_obj=models.Child.objects.get (name= "tiger") colors_obj=models.Colors.objects.all () child_obj.favor=colors_objchild_obj.save () # make tiger like yellow and blue (2 words are the same as above Show only one way to write) child_obj=models.Child.objects.get (name= "tiger") colors_obj=models.Colors.objects.filter (colors__in= ["blue", "yellow"]) # models can only get union in this way by default. For more complex filtering logic, you need to use the module Qchild_obj.favor.clear () # to clear Xiaohu's favorite color child_obj.favor.add (* colors_obj) # add is an append mode. If the current tiger already likes green, then after execution, the tiger will extra like blue, and yellow # will make the tiger like green (the two words are the same as above. Show only one way to write) child_obj=models.Child.objects.get (name= "tiger") colors_obj=models.Colors.objects.get (colors= "green") child_obj.favor.clear () child_obj.favor.add (colors_obj) # there is no * # add parent table association # Let people who like blue add tiger, you can use the above method, an effect, let tiger like blue The following describes the reverse insertion (starting with the parent table) child_obj=models.Child.objects.get (name= "tiger") colors_obj=models.Colors.objects.get (colors= "blue") colors_obj.child_set.add (child_obj) # insert the tiger from the colors table, writing: parent object. The child table name is lowercase _ set.add (child table object). Let the child_set collection that likes blue add name= "tiger" # Let everyone like blue children_obj=models.Child.objects.all () colors_obj=models.Colors.objects.get (colors= "blue") colors_obj.child_set.add (* children_obj) # about the writing of _ set, whether you are a little dizzy, when to use _ set, simple memory, only the child table has the writing of "subtable name lowercase _ set", what you get is a QuerySet collection. It can be followed by .add (), .remove (), .update (), .delete (), .clear () # and note that colors_obj.child_set.clear () removes blue from everyone's favorite color, and colors_obj.child_set.all () .delete () is the owner who deletes .child _ set.
Delete:
Delete many-to-many table relationships:
# delete the relationship between the child table and the parent table # Let the tiger not like any color # write 1:child_obj=models.Child.objects.get (name= "tiger") colors_obj=models.Colors.objects.all () child_obj.favor=''child_obj.save () # write 2:child_obj=models.Child.objects.get (name= "tiger") colors_obj=models.Colors.objects.all () child_obj.favor.remove (* colors_obj) # write 3:child _ obj=models.Child.objects.get (name= "Tiger") child_obj.favor.clear () # other examples refer to many-to-many add and change cases No examples are given here # deleting the association between parent and child tables # makes everyone no longer like blue # write 1:children_obj=models.Child.objects.all () colors_obj=models.Colors.objects.get (colors= "blue") colors_obj.child_set.remove (* children_obj) # write 2:colors_obj=models.Colors.objects.get (colors= "blue") colors_obj.child_set.clear ()
Delete many-to-many table data:
# Delete child table data # everyone who likes blue deletes colors_obj=models.Colors.objects.get (colors= "blue") colors_obj.child_set.all (). Delete () # Note: .all () # Delete all childmodels.Child.objects.all () .delete ()
Delete the parent table data:
By default, if the "red" color is deleted in this example, the subtable has an one-to-one or foreign key relationship with the color table, and the corresponding data of the subtable will be deleted automatically, such as Red Ball, Brother Tiger.
If there is a many-to-many relationship with the color table, people who like red will not be automatically deleted, but red will be removed.
If you want the child table associated with the foreign key of the parent table to retain the data of the child table after the foreign key is deleted, add the following fields when you need the child table to create the table:
Class Clothes (models.Model): color=models.ForeignKey ("Colors", null=True,on_delete=models.SET_NULL)) # can be empty. If the foreign key is deleted, the child table data this field is left empty instead of deleting the data directly. Similarly, you can also SET_DEFAULT. This field needs to be described by the default value description=models.CharField (max_length=10) #.
Choice
# choices is equivalent to implementing a simplified version of foreign keys. The options of foreign keys cannot be dynamically updated, such as fewer optional items. You can use # to add the choices field class Child (models.Model): sex_choice= ((0, "male"), (1, "female") name=models.CharField (max_length=10) # name favor=models.ManyToManyField ('Colors') # and color table for many-to-many sex=models.IntegerField (choices=sex_choice) Default=0) def _ unicode__ (self): return self.name# calls child_obj=models.Child.objects.get (name= "Tiger") print (child_obj.sex) # in views.py and returns 0 or 1print (child_obj.get_sex_display ()) # male or female thank you for reading this article carefully I hope the article "one-to-one, one-to-many, many-to-many example Analysis based on ORM in Django" shared by the editor will be helpful to everyone. At the same time, I also hope that you will support and pay attention to the industry information channel. More related knowledge is waiting for you 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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.