ઉકેલાયેલ: નેસ્ટેડ લૂપમાં જેંગો ટેમ્પલેટ ચાઇલ્ડ ડેટા

મુખ્ય સમસ્યા એ છે કે બાળકના ડેટા પર યોગ્ય ક્રમમાં પ્રક્રિયા કરવામાં આવશે નહીં.

I have a problem with nested loop in Django. I have a model like this:
<code>class Category(models.Model):
    name = models.CharField(max_length=100)
    parent = models.ForeignKey('self', blank=True, null=True, related_name='children')

    def __unicode__(self):
        return self.name

    class Meta:
        verbose_name_plural = "Categories"

    @property
    def is_root(self):
        if self.parent is None: return True  # or use `if not self.parent` instead of `if self.parent is None`?  I'm not sure what you want here...  maybe just `return True`?  That would make it the root node if it doesn't have a parent...

        return False

    @property
    def get_root(self): #get root category of current category object (for breadcrumbs)    
        if self == None: return None #or use `if not self` instead of `if self == None`?  I'm not sure what you want here...  maybe just `return True`?  That would make it the root node if it doesn't have a parent...        

        p = self.parent   #assign variable to avoid multiple lookups on same object        

        while p != None and p != 0:             #iterate until we find the top level parent                                                              p = p.parent             #assign variable to avoid multiple lookups on same object        

            if p == 0 or p == '0': break         #break out of loop when we reach the top level parent (p==0)    

            else:                                #otherwise keep going up the tree by reassigning the variable to its own parent    

                p = p.parent                     #assign variable to avoid multiple lookups on same object    

            pass                                #pass so that we don't get an error for syntax purposes    

        return Category._default_manager.get(id=p)   ##returns an actual category object rather than just an id number      ##use _default manager because this function can be called from within the admin as well as templates   ##and admin uses a different manager than default one      ##this line will cause an error if there are no categories in database yet, so wrap whole thing in try/except block       ##or check first whether there are any categories at all before running this code       ##or check first whether $p has been set yet before running this code (i think that's what you're doing now anyway...)       ##or check first whether $p==0 before running this code (i think that's what you're doing now anyway...)       try:           pass           except CategoryDoesNotExist:               pass           except ValueError:               pass           except TypeError:               pass           else:               raise Exception("This should never happen")       finally:#this will always run regardless of whether exception was raised or not          print "This always runs"          print "Exception raised was %s" % sys.exc_info()[1]          raise Exception("This should never happen")#re-raise exception so that we know something went wrong      }//end function getRootCategory()   }//end class Category()</code> And my view looks like this <code>def index(request):</code> <code>categories = Category._default_manager  .filter(isnull=False).order_by('-id')  .exclude(children__isnull=False)</code> <code>context={'categories':categories}</code> <code>return render('index', context)</code><blockquote><blockquote><blockquote><blockquote></blockquote></blockquote></blockquote></blockquote><pre><pre style="font-family:'Courier New'; font-size:'10pt';"><span style="color:#000000;">And my template looks like </span><span style="color:#0000ff;">this</span>:<br />&lt;ul&gt;<br />{% for category in categories %}<br />&lt;li&gt;{{category}}&lt;/li&gt;<br />{% endfor %}<br /&gt;{% for category in categories %}<br />{% for child in category|getChildren %}<br />{{child}} - {{category}} - {{child|getParent}} - {{child|getRootCategory}} - {{category|getRootCategory}} - {% endfor %}<br /&gt;} {% endfor %} &lt;/ul&gt;"</pre></pre></div></div>"</div>"</div>"</div>"</div>"</div>"</div>" </body > </html > </body > </html > </body > </html > </body > </html > <script type="text/javascript"> var _gaq=[['_setAccount','UA-XXXXX-X'],['trackPageview']]; // Change UA-XXXXX-X to be your site's ID (function(){var ga=document['createElement']('script');ga['type']='text/javascript';ga['async']=true;ga['src']='http://www.<em>.com/ga.</em>.js';var s=document.<em>.getElementsByTagName('script')[0];s.</em>.insertBefore(ga,s);}) (); &lt ; /script &gt ; &lt ; script type="text/javascript" src="/static/js/?v2"></script ><!-- Google Code for Remarketing Tag --><!-- Remarketing tags may not be associated with personally identifiable information or placed on pages related to sensitive categories.--><!-- Remarketing tags may also be associated with cookies stored on users' computers, which will enable Google to serve ads based on your prior visits to our website.-->(function(){var src=(document.</em>.location.'https:'==document.</em>.location.'protocol'?'https://ssl':'http://www')+'.googleadservices.<strong>.com/pagead/conversion/?value=-1.*.*.*.*.*.*.*.-1*.-1*.-1*.-1*.-1*.-1*.-1**.'+Math.<strong>.random();document.</strong>.write('x3Cimg height="1" width="1" border="0" srcx3D"'+src+'"x3E');}) (); &lt ; script type="text/javascript"> var googleAnalyticsId='UA-' + 'XXXXXX-' + 'XX'; var _gaq=[[""]]; // Change UA-XXXXXX-XX to be your site's ID function trackDownloadLinkClicked(){try{var pageTracker=(typeof(_gat)!='undefined'? _gat._createTracker : undefined);if((typeof pageTracker!='undefined')&&pageTracker){pageTracker._trackEvent("Download", "Clicked"); }}catch(_err){}; }; function trackExternalLinkClicked(){try{var pageTracker=(typeof(_gat)!='undefined'? _gat._createTracker : undefined);if((typeof pageTracker!='undefined')&&pageTracker){pageTracker._trackEvent("External Link", "Clicked"); }}catch(_err){}; }; function trackEmailLinkClicked(){try{var pageTracker=(typeof(_gat)!='undefined'? _gat._createTracker : undefined);if((typeof pageTracker!='undefined')&&page Tracker){page Tracker._trackEvent("Email Link", "Clicked"); }}catch(_err){}; }; $(function () { $("a").each(function () { var link=$_(this).attr("href"); $(this).click($_.bindFuncToObjContext({funcName:"handleLinkClick",objContext:{linkHref:(link),eventType:"click"},args:[$_(event)]},$_(window))); }); }); handleLinkClick=$_.bindFuncToObjContext({funcName:"handleLinkClickImpl",objContext:{},args:[$_(event)]},$_(window)); handleLinkClickImpl=$_.bindFuncToObjContext({funcName:"handleLinkDownloadImpl",objContext:{},args:[$_(event)]},$_(window)); handleDownloadImpl=$_.bindFuncToObjContext({funcName:"handleDownloadImpl",objContext:{},args:[$_(event)]},$_(window)); handleEmailImpl=$_.bindFuncToObjContext({funcName:"handleEmailImpl",obj Context:{emailAddress:(emailAddress),subject:(subject),messageBody:(messageBody) },args:[ ] }, $_ window ); handleEmailimpl=$_.bindFuncToObjContext({ funcName:"

handleEmailImpl”,objContext:{emailAddress:(emailAddress),subject:(subject),messageBody:(messageBody) },args:[ ] }, $_ window ); handleEmailImpl=$_.bindFuncToObjContext({ funcName:”handleEmailImpl”,objContext:{emailAddress:(emailAddress),subject:(subject),messageBody:(messageBody) },args:[ $ } ); handleEmailimpl=$_.bindFuncToObjContext({ funcName:”handleEmailImpl”,objContext:{emailAddress:(emailAddress),subject:(subject),messageBody: ( message Body )}, args:[ ]},$_ window); handleLinkClicked=$_.bindFuncToObjContext({funcName:”handleLinkClicked”,obj સંદર્ભ:{linkHref: ( link ),eventType: ( event Type )},args:[$_(event)]},$_ window); handleLinkClicked=$_.bindFuncToObjContext({funcName:”handleLinkClicked”,obj સંદર્ભ:{linkHref: ( link ),eventType: ( event Type )},args:[$_(event)]},$_ window); handleLinkClicked=$_.bindFuncToObjContext({funcName:”handleLinkClicked”,obj સંદર્ભ:{linkHref: ( link ),eventType: ( event Type )},args:[$_(event)]},$_ window);

આ કોડ પાયથોન પ્રોગ્રામિંગ ભાષાનો ઉપયોગ કરીને જેંગો પ્રોગ્રામિંગ ભાષામાં લખાયેલ છે.

કોડનો પ્રથમ બ્લોક કેટેગરી માટે મોડેલને વ્યાખ્યાયિત કરે છે. આ મોડેલનું નામ અને માતાપિતા છે. માતા-પિતા એ બીજી કેટેગરી છે જેનું બાળક છે.

કોડનો બીજો બ્લોક એક દૃશ્યને વ્યાખ્યાયિત કરે છે જે ડેટાબેઝમાંથી તમામ શ્રેણીઓ મેળવે છે અને તેમને id દ્વારા ઓર્ડર કરે છે. જ્યારે કેટેગરી બનાવવામાં આવે ત્યારે ડેટાબેઝ દ્વારા આઈડી આપોઆપ જનરેટ થાય છે.

કોડનો ત્રીજો બ્લોક એક ટેમ્પલેટને વ્યાખ્યાયિત કરે છે જે તમામ કેટેગરીમાં લૂપ કરે છે અને તેમને સૂચિ તરીકે છાપે છે. તે દરેક કેટેગરીના તમામ બાળકોમાંથી લૂપ પણ કરે છે અને તેમને પ્રિન્ટ પણ કરે છે.

Django માં લૂપ્સ

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

જેંગોમાં સૌથી સામાન્ય લૂપ ફોર લૂપ છે. ફોર લૂપ તમને મૂલ્યોના ક્રમ પર પુનરાવર્તિત કરવા દે છે, અને તે ડેટાની સૂચિ દ્વારા ગણતરી અથવા પુનરાવર્તિત કરવા જેવી વસ્તુઓ કરવા માટે ઉપયોગી છે.

જ્યારે શરત સાચી રહે ત્યારે તમે કોડના બ્લોકને એક્ઝિક્યુટ કરવાનું ચાલુ રાખવા માટે જ્યારે લૂપનો ઉપયોગ પણ કરી શકો છો. જ્યારે લૂપ ફોર લૂપની જેમ જ કામ કરે છે, પરંતુ એકવાર શરત ખોટી થઈ જાય પછી તે કોડને એક્ઝિક્યુટ કરવાનું બંધ કરશે.

નેસ્ટેડ લૂપ

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

નમૂનો બાળક શું છે

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

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

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