Generic relation and reverse resource URI?

59 views
Skip to first unread message

Stodge

unread,
Mar 7, 2016, 9:34:56 AM3/7/16
to Tastypie
I'm trying to use generic relations with TastyPie but I'm not having much luck. My models are:

class CalendarEntry(models.Model):
    
# Mappings between content and an event entry.
    content_type    
= models.ForeignKey(ContentType, verbose_name='content type')
    object_id       
= models.PositiveIntegerField()
    content_object  
= generic.GenericForeignKey('content_type', 'object_id')
    field           
= models.CharField(max_length=64)
    
....



class Event(ProtectedModel):
    
event = generic.GenericRelation(CalendarEntry)
    
....


My resources are:

class CalendarEntryResource(...):
    content_object 
= GenericForeignKeyField({
        
Event: EventResource
    
}, 'content_object', null=True, blank=True)
    
....


class EventResource(...):
    
# How do I define event here?
    
#event = fields.ForeignKey('CalendarEntryResource', 'event', full=False, null=False, blank=False, unique=False)



When I perform an HTTP GET for the events:
 
    /event/api/v1/event/

I get:
  • objects
    [
    • {
      • _content_excerpt"<p>d</p>",
      • author"/accounts/api/v1/user/5/",
      • content"<p>d</p> ",
      • created"2016-03-05T20:37:43.470623",
      • id1,
      • language"en",
      • resource_uri"/event/api/v1/event/1/",
      • title"Text",
      • updated"2016-03-05T20:37:43.470650"
      }
    ]

But the event field (generic object) is missing. How do I get it included in the resource?

If I get all calendar entries:

    /calendar/api/v1/calendar-entry/

I get:

  • objects
    [
    • {
      • all_daytrue,
      • calendars
        [
        • "/calendar/api/v1/calendar/5/"
        ],
      • colour"#580000 ",
      • content_object"/event/api/v1/event/1/",
      • end_date"2016-03-30T15:37:00",
      • end_repeatnull,
      • field"event",
      • id1,
      • object"/event/api/v1/event/1",
      • object_id1,
      • recurring_events: [ ],
      • repeat"NEVER",
      • resource_uri"/calendar/api/v1/calendar-entry/1/",
      • start_date"2016-03-09T15:37:00",
      • title"Test",
      • url"/event/event/1/"
      }
    ]
Which looks correct to me.

Thanks
Mike

Stodge

unread,
Mar 7, 2016, 10:13:24 AM3/7/16
to Tastypie
Ok, I added the following to the EventResource:

    event = fields.ManyToManyField(
        'CalendarEntryResource',
        'event',
        related_name='content_object',
        full=False
    )

Which works, but it's supposed to be a one to one mapping, so there will only ever be one CalendarEntry pointing to the Event. But if it's supposed to work this way and I don't have a choice.. :)
Reply all
Reply to author
Forward
0 new messages