您好,登錄后才能下訂單哦!
這篇文章將為大家詳細講解有關(guān)如何在Django中使用ManyToManyField save方法實現(xiàn)多表關(guān)聯(lián),文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關(guān)知識有一定的了解。
當(dāng)models中使用ManyToManyField進行多表關(guān)聯(lián)的時候,需要使用字段的add()方法來增加關(guān)聯(lián)關(guān)系的一條記錄,讓兩個實例關(guān)聯(lián)起來才能順利保存關(guān)聯(lián)關(guān)系
#models.py 問題分類question_category和類別使用了多對多關(guān)系(先不管是否合理) #coding:utf-8 from django.db import models # Create your models here. class QuestionCategory(models.Model): category_name = models.CharField('問題分類',max_length=50) def __unicode__(self): return self.category_name class Question(models.Model): question_category = models.ManyToManyField(QuestionCategory,verbose_name="歸屬分類") question_title = models.CharField('標(biāo)題', max_length=50) question_author = models.ForeignKey('auth.User', blank=True, null=True,verbose_name='作者') question_keywords = models.CharField('關(guān)鍵詞',max_length=20) question_date = models.DateTimeField('date published') question_text = models.CharField('正文內(nèi)容', max_length=200) def __unicode__(self): return self.question_title
#QuestionCategory.objects.get生成一個類別實例 #request.POST從前端獲取表單提交的數(shù)據(jù)后,湊到Question里面形成一個問題實例 #先把問題實例存好,再在問題實例的多對多關(guān)聯(lián)字段question_category上添加關(guān)聯(lián)對象joe這個類別實例,關(guān)聯(lián)好之后再save第二遍,查看數(shù)據(jù)庫里面關(guān)聯(lián)關(guān)系就存好了 def ask_question(request): question_category_name = request.POST['radio'] question_title = request.POST['question_title'] question_keywords = request.POST['question_keywords'] question_text = request.POST['question_content'] question_date = datetime.datetime.now() question_author = request.user joe = QuestionCategory.objects.get(category_name=question_category_name) print joe qqqq = Question(question_title=question_title,question_keywords=question_keywords,question_date=question_date,question_text=question_text,question_author=question_author) qqqq.save() qqqq.question_category.add(joe) qqqq.save() return redirect('pythonnav:index')
關(guān)于如何在Django中使用ManyToManyField save方法實現(xiàn)多表關(guān)聯(lián)就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。