0

I have a model, Entry with a Foreign Key, author, of type User:

author = models.ForeignKey(User, default=None)

I periodically poll the server using AJAX and have a view that returns any new Entry objects in a response, serialized in JSON format. Here is the code:

def pollNewEntries(request):
    if request.method == 'GET':
        delta = datetime.timedelta(seconds=19)

        # Determine if there are any new posts since 19 seconds before current
        # time. AJAX polls server every 10 seconds. Stores ids of new posts and
        # checks those against any incoming posts, ignoring duplicates. 

        cutOff = timezone.now() - delta
        newEntries = Entry.objects.filter(pubDate__gt=cutOff)
        data = serializers.serialize('json', newEntries)
        return HttpResponse(data, mimetype='application/json')

This returns completely fine data for all of the rest of my Entry fields, but when I dynamically log/print/append Entry.author in my Javascript, it gives me the id field of the author. I've inspected the serialized object in the JS, and there are no additional fields in author to get.

Is there a way to change what part of author is represented in the serialized data? Basically, I want my view to return a JSON object that has author.name instead of author.id for the author field.

4

1 に答える 1

0

自然キーを定義すると思われます:

from django.db import models

class PersonManager(models.Manager):
    def get_by_natural_key(self, first_name, last_name):
        return self.get(name=first_name)

class Person(models.Model):
    objects = PersonManager()

    name = models.CharField(max_length=100)

    birthdate = models.DateField()

class Meta:
    unique_together = (('name'),)

あなたが望むものを達成することができるでしょう。

于 2013-05-13T14:04:48.943 に答える