ઉકેલાયેલ: સંબંધિત ક્ષેત્ર manytoamny django%5D માં ઘણા ઉદાહરણો ઉમેરો

સંબંધિત ક્ષેત્રમાં ઘણા ઉદાહરણો ઉમેરવા સંબંધિત મુખ્ય સમસ્યા એ છે કે તે પ્રદર્શન સમસ્યાઓનું કારણ બની શકે છે. આ એટલા માટે છે કારણ કે ડેટાબેઝને તમામ ઉદાહરણોનો ટ્રૅક રાખવો પડશે, અને આ ધીમી કામગીરી તરફ દોરી શકે છે.

%5B%5D=1&django%5D%5B%5D=2&django%5D%5B%5D=3

I have a model with a many to many relationship:
<code>class MyModel(models.Model):
    related_field = models.ManyToManyField(RelatedModel)
</code>
In the admin interface, I can add multiple instances of <code>RelatedModel</code> to <code>related_field</code>.  How can I do this in code?  The following doesn't work:
<code>mymodel = MyModel()
mymodel.related_field = [1, 2, 3] # doesn't work!  only adds 1 instance of RelatedModel to related_field.  
mymodel.save() # only saves one instance of RelatedModel in related_field!  
</code>


A:

    mymodel = MyModel()     mymodel.save()     mymodel.related_field = [1, 2, 3]     mymodel.save() 

ઘણા થી ઘણા સંબંધો

ઘણા-થી-ઘણા સંબંધો એ બે એન્ટિટી વચ્ચેના સંબંધનો એક પ્રકાર છે જ્યાં દરેક એન્ટિટી બીજા સાથે બહુવિધ સંબંધો ધરાવી શકે છે. ઉદાહરણ તરીકે, એક વ્યક્તિ પાસે ઘણા મિત્રો હોઈ શકે છે, અને મિત્ર પાસે ઘણા લોકો હોઈ શકે છે જેની સાથે તે મિત્રો છે. જેંગોમાં, ઘણા-થી-ઘણા સંબંધને બે ક્ષેત્રો ધરાવતા મોડેલ ઉદાહરણ દ્વારા રજૂ કરવામાં આવે છે: એક પ્રથમ એન્ટિટી માટે અને એક બીજી એન્ટિટી માટે.

ManyToMany સંબંધમાં બહુવિધ વસ્તુઓ કેવી રીતે ઉમેરવી

Django માં ManyToMany સંબંધમાં બહુવિધ ઑબ્જેક્ટ ઉમેરવા માટે, તમે many_to_many ઑબ્જેક્ટ પર add() પદ્ધતિનો ઉપયોગ કરી શકો છો. ઉદાહરણ તરીકે, Django માં many_to_many સંબંધ બ્લોગ પોસ્ટમાં બ્લોગ પોસ્ટ અને લેખક ઉમેરવા માટે, તમે નીચેના કોડનો ઉપયોગ કરશો:

blog.add(BlogPost.objects.create(title='Adding Multiple Objects to a ManyToMany Relationship', content=content)) author = Author.objects.create(name='John Doe')

તમે એક પરિણામ સમૂહમાં ઑબ્જેક્ટને જોડવા માટે many_to_many ઑબ્જેક્ટ પર join() પદ્ધતિનો પણ ઉપયોગ કરી શકો છો:

blog.join(લેખક)

સંબંધિત પોસ્ટ્સ:

પ્રતિક્રિયા આપો