Tastypie的外键

时间:2012-10-25 17:00:38

标签: python django tastypie

我遇到这样的问题:实施许多城市的选举制度。

  • 每个城市最多有3名候选人
  • 城市状况为:选举开放

这是我的模特:

class City(models.Model):
ELECTION_CLOSED = -1
ELECTION_OPENNING = 0
ELECTION_BEGIN = 1

ELECTION_STATUSES = (
        (ELECTION_CLOSED,"Election closed"),
        (ELECTION_OPENNING,"Election Openning"),
        (ELECTION_BEGIN, "Election Begin"),
)
city = models.ForeignKey(Location,related_name='location')
president = models.ForeignKey(User,related_name='president',default=None,blank=True,null=False)
election_status = models.IntegerField(choices=ELECTION_STATUSES,default=ELECTION_OPENNING)
start_electing_at = models.DateTimeField(auto_now_add=True)
start_president_at = models.DateTimeField(auto_now_add=True)


class Candidate(models.Model):
    city = models.ForeignKey(Location)
    candidate = models.ForeignKey(User,related_name='votegame_candidate_id')
    num_of_votes = models.PositiveIntegerField(default=0)

这是我的资源

class CityResource(ModelResource):
city = fields.ToOneField(LocationResource, 'city')
class Meta:
    allowed_methods = ['post','get']
    queryset = City.objects.all()

class CandidateResource(ModelResource):
    city = fields.ToOneField(LocationResource, 'city')
    candidate = fields.ToOneField(UserResource, 'candidate')

class Meta:
    allowed_methods = ['post','get']
    include_resource_uri = False
    queryset = Candidate.objects.all()
    always_return_data = True
    authentication = BasicAuthentication()
    authorization= Authorization()
    filtering = {"city": ALL }
def obj_create(self, bundle, request=None, **kwargs):
    city_res = self.city.get_related_resource(self)
    print city_res.id

**#######I want to check if the City status is "Election Openning" here####**

    userbalance,created = Balance.objects.get_or_create(user=request.user)
    obj = self.obj_get_list(request,city=bundle.data.get("city"))
**#######I want to check if the number of Candidates in the city is now 3 here ######**

    try:
        bundle= super(CandidateResource, self).obj_create(bundle, request, user=request.user)
    except IntegrityError,e:
        print e

    return bundle

见上面我的2个问题? 我运行POST:

curl --dump-header - -H "Content-Type: application/json" -X POST --data '{"city" : "/votegame/v1_votegame/city/123/"}' http://127.0.0.1:8000/votegame/v1_votegame/candidate/ -u summer:123456

问题1:

#I想要检查城市状态是否为“选举开放”

我做:print city_res.id,我得到<tastypie.fields.CharField object at 0xb50d7ecc>

问题2:

#I想检查这个城市的候选人数目现在是3

print obj时我什么都没得到 但如果我改为

obj = self.obj_get_list(request,city="123")

我得到了清单。

任何人都可以给我一些想法。 非常感谢你。

0 个答案:

没有答案