ઉકેલાયેલ: ડીજેંગોમાં ઘણા બધા ક્ષેત્રમાં બનાવો અને ઉમેરો

Django માં ઘણા બધા ક્ષેત્રો બનાવવા અને ઉમેરવામાં મુખ્ય સમસ્યા એ છે કે ડેટાને યોગ્ય રીતે સંચાલિત કરવું મુશ્કેલ બની શકે છે. આ એટલા માટે છે કારણ કે કયા રેકોર્ડ કયા ફીલ્ડના છે તેનો ટ્રેક રાખવો મુશ્કેલ બની શકે છે અને આપેલ રેકોર્ડ માટે કયા ફીલ્ડની જરૂર છે તે નક્કી કરવું મુશ્કેલ બની શકે છે.

મારી પાસે ઘણા બધા ક્ષેત્રો સાથેનું મોડેલ છે:
class MyModel(models.Model):
name = models.CharField(max_length=50)
tags = models.ManyToManyField('Tag')

def __unicode__(self):
return self.name

હું એક નવો દાખલો બનાવવા માંગુ છું MyModel, અને યાદી ઉમેરો Tag માટે પદાર્થો tags ક્ષેત્ર:
my_model = MyModel() # Create new instance of MyModel without saving it yet.
my_model.name = 'foo' # Set the name field on the new instance.
tag1 = Tag() # Create first Tag object without saving it yet.
tag1.name = 'bar' # Set the name field on the first Tag object.
tag2 = Tag() # Create second Tag object without saving it yet.
tag2.name = 'baz' # Set the name field on the second Tag object.

my_model_tags=[tag1, tag2]# Add both tags to my list of tags for my model

my_model=MyModel(tags=my_model_tags)# Add both tags to my model's tags field and save everything in one go!

my_model=MyModel()#Create new instance of MyModel without saving it yet again! This time we'll add some existing Tags from our database instead of creating them from scratch like we did above!

tag3=Tag().objects('id': 1)#Get an existing tag from our database by its id number and store it in a variable called "tag3"

tag4=Tag().objects('id': 2)#Get another existing tag from our database by its id number and store it in a variable called "tag4"

my_model2Tags=[tag3, tag4]#Add both tags (which already exist in our database) to my list of tags for my model this time around!

my_model2=MyModel(tags=myModeltags2)#Add both tags (which already exist in our database) to my model's "tags" field and save everything in one go again! Hooray! Now all four Tags are associated with this one MyModeL instance that we created, two of which were created right here while two others were pulled straight out of our database! All using just two lines each time around too boot!!! :D :D :D Yippee!!! :) :) :) </pre></blockquote><p>Note that you can also do this:</p><blockquote style="margin: 0px 0px 0px 40px;" class="speaker-notes-content-element speaker-notes-content-element--s1" data-highlighted="" data-speaker-notes="" data-end="1518106096000" data-start="1518106096000" tabindex="0" contenteditable="false" spellcheck="false" role="textbox" data-previouscontenteditablevalue="" draggable="true">

myModeltags=[Tag().objects('id': 1), Tag().objects('id': 2)]   </pre></blockquote>", "type": "rich", "version": 1}]}], "type": "rich", "version": 1}]}], [{"data": {"text/html": "

https://..com/#!/slide/1518105754911

""}

Related posts:

Leave a Comment