Django选择具有特定列的查询

时间:2011-05-15 08:18:23

标签: django django-models django-queryset

我有一个名为MessagePerson的模型,其中包含描述特定人的消息的详细信息字段,其详细信息位于Personal模型中。

我甚至有一个单独的模型,它具有Personal类的外键引用。

class Personal(models.Model):
    name = models.CharField(max_length=20,primary_key=True)
    email = models.EmailField(blank=True,null=True)
    address = models.CharField(max_length=50,blank=True,null=True)
    contact =  models.CharField(max_length=20)
    pic = models.FileField(upload_to='image/',blank=True,null=True)

    def __unicode__(self):
        return self.name    

class MessagePerson(models.Model):
    person = models.ForeignKey(Personal, related_name='msg')
    mname = models.CharField(max_length=30)
    mPhone = models.CharField(max_length=20,blank=True,null=True)
    memail = models.EmailField(blank=True,null=True)
    message = models.CharField(max_length=200,blank=True,null=True)

    def __unicode__(self):
        return self.person.name

class GData(models.Model):
    person = models.ForeignKey(Personal, related_name='everyperson')
    place = models.CharField(max_length=40)
    typeOfProperty = models.CharField(max_length=30)
    typeOfPlace = models.CharField(max_length=20)
    price = models.IntegerField()
    def __unicode__(self):
        return self.person.name

现在我需要的是,我有id GData使用,我应该为特定的'MessagePerson using name of个人

保存一条消息

我使用的查询是: Views.py

def message(request, g_id):
    n = request.POST['bname']
    p = request.POST['bphone']
    e = request.POST['bemail']
    m = request.POST['bmsg']

    mperson = GData.objects.get(id=g_id).values('person')

    msg_job = MessagePerson(person=mperson, mname=n, mPhone=p, memail=e, message=m)
    msg_job.save()
    return render_to_response('ivent.html', context_instance=RequestContext(request))

现在的事情是,没有任何错误,它甚至没有存储消息:(

请帮助我得到结果:(

1 个答案:

答案 0 :(得分:9)

突出的是:

mperson = GData.objects.get(id=g_id).values('person')

应该是:

mperson = GData.objects.get(id=g_id).person

您也应该重新考虑一下您的视图逻辑,只是快速查看这样的事情稍微好一些,但可能会有所改进:

from django.shortcuts import get_object_or_404 

def message(request, g_id):
    mperson = get_objects_or_404(GData, id=g_id).person

    if request.method == 'POST':
        n = request.POST.get('bname')
        p = request.POST.get('bphone')
        e = request.POST.get('bemail')
        m = request.POST.get('bmsg')
        msg_job = MessagePerson(person=mperson, mname=n, mPhone=p, memail=e, message=m)
        msg_job.save()
        return render_to_response('ivent.html', context_instance=RequestContext(request))

    return HttpResponse('Not a post request')