Bootcamp: Alimentar con diferentes tipos de alimentos

Creado en 6 dic. 2017  ·  9Comentarios  ·  Fuente: vitorfs/bootcamp

Estoy intentando implementar 3 tipos de alimentación:

  1. Estado (feed de mensajes)
  2. Alimentación de video
  3. Feed de imágenes

Estoy usando la clase de alimentación , el tipo de alimentación y para cada tipo una clase específica, pero no sé cómo conectar la clase de alimentación con cada clase de tipo (clase de video, clase de imagen)

¿Cualquier sugerencia?

Gracias por el apoyo

Support enhancement question

Todos 9 comentarios

@ sebastian-code Me doy cuenta de esta característica, pero no sé cómo puedo obtener los campos adicionales de la imagen o del video dentro de la vista.

Este es mi codigo:

<strong i="7">@python_2_unicode_compatible</strong>
class Feed(models.Model):
    #STATUS OF FEEDS
    DRAFT       = 'D'
    PUBLISHED   = 'P'
    INVISIBLE   = 'I'
    VISIBLE     = 'V'

    # #TYPE OF FEEDS
    TYPE_STATUS = 'STATUS'
    # TYPE_IMG = 'IMAGE'
    # TYPE_VOD = 'VIDEO'
    # TYPE_MATCH = 'MATCH'

    STATUS = (
        (DRAFT, 'Draft'),
        (PUBLISHED, 'Published'),
    )


    user            = models.ForeignKey(User)
    date            = models.DateTimeField(auto_now_add=True)
    post            = models.TextField()
    parent          = models.ForeignKey('Feed', null=True, blank=True)
    likes           = models.IntegerField(default=0)
    comments        = models.IntegerField(default=0)
    #post_type   = models.TextField(null=True, blank=True)
    #media_url   = models.TextField(null=True, blank=True)

    media_url       = None
    #Custom fields
    post_type       = models.ForeignKey('FeedType')
    status          = models.CharField(max_length=1, choices=STATUS, default=DRAFT)
    tags            = TaggableManager()
    specific_post   = models.IntegerField(default=0)

    class Meta:
        verbose_name = _('Feed')
        verbose_name_plural = _('Feeds')
        ordering = ('-date',)

#
class FeedType(models.Model):

    feed_type = models.CharField(max_length=255, default=Feed.TYPE_STATUS)

    class Meta:
        verbose_name = _('FeedType')
        verbose_name_plural = _('FeedTypes')
        ordering = ('pk',)

    def __str__(self):
        return self.feed_type

    #method
    <strong i="8">@staticmethod</strong>
    def get_status_type():
        print("get_status_type();")
        feed_type = FeedType.objects.get(pk=1)
        return feed_type

    <strong i="9">@staticmethod</strong>
    def get_image_type():
        print("get_image_type();")
        feed_type = FeedType.objects.get(pk=2)
        return feed_type

    <strong i="10">@staticmethod</strong>
    def get_video_type():
        print("get_video_type();")
        feed_type = FeedType.objects.get(pk=3)
        return feed_type

    <strong i="11">@staticmethod</strong>
    def get_match_type():
        print("get_match_type();")
        feed_type = FeedType.objects.get(pk=4)
        return feed_type

'''
    IMAGE  FEED
'''
class ImageRelationsMixin(object):

    class FeedManagerMeta:
        image_feed = 'feeds.ImageFeed'

    <strong i="12">@property</strong>
    def Feed(self):
        feed_model_path = getattr(self.FeedManagerMeta, 'feed', 'feeds.ImageFeed')

        #print(django_get_model(*feed_model_path.split('.')))
        return django_get_model(*feed_model_path.split('.'))

class ImageFeedMixin(ImageRelationsMixin, models.Model):
    """ImageFeed represents .

    :Parameters:
      - ``: member's first name (required)
    """
    content_url = models.TextField(null=True, blank=True, default='')

    class Meta:
        abstract = True

    def __unicode__(self):
        return self.post

    def __str__(self):
        return self.post

class ImageFeed(Feed, ImageFeedMixin):

    '''django_user = models.ForeignKey(DjangoUser, null=True, blank=True, on_delete=models.SET_NULL,
                                    related_name='%(app_label)s_%(class)s_set')'''
    django_feed = models.ForeignKey(Feed, null=True, blank=True, on_delete=models.SET_NULL,
                                    related_name='%(app_label)s_%(class)s_set')

    # this is just required for easy explanation
    class Meta(ImageFeedMixin.Meta):
        abstract = False


'''
    Video  FEED
'''
class VideoRelationsMixin(object):

    class FeedManagerMeta:
        video_feed = 'feeds.VideoFeed'

    <strong i="13">@property</strong>
    def Feed(self):
        feed_model_path = getattr(self.FeedManagerMeta, 'feed', 'feeds.VideoFeed')
        #print(django_get_model(*feed_model_path.split('.')))
        return django_get_model(*feed_model_path.split('.'))

class VideoFeedMixin(VideoRelationsMixin, models.Model):
    """VideoFeed represents .

    :Parameters:
      - `media_url`: member's first name (required)
    """
    content_url = models.TextField(null=True, blank=True, default='')

    class Meta:
        abstract = True

    def __unicode__(self):
        return self.post

    def __str__(self):
        return self.post

#Feed di tipo Video
class VideoFeed(Feed, VideoFeedMixin):

    django_feed = models.ForeignKey(Feed, null=True, blank=True, on_delete=models.SET_NULL,
                                    related_name='%(app_label)s_%(class)s_set')

    # this is just required for easy explanation
    class Meta(VideoFeedMixin.Meta):
        abstract = False

Este es el clásico view.py

<strong i="6">@login_required</strong>
def feeds(request):
    all_feeds = Feed.get_feeds()
    paginator = Paginator(all_feeds, FEEDS_NUM_PAGES)
    feeds = paginator.page(1)
    from_feed = -1
    vip = Feed.get_talentini(request.user)
    user_vip = Feed.get_user_talentino(request.user)

    if feeds:
        from_feed = feeds[0].id
    return render(request, 'feeds/feeds.html', {
        'feeds': feeds,
        'from_feed': from_feed,
        'page': 1,
        'vip':vip,
        'user_vip':user_vip
        })

¡Nada de lo que resolví!

screen shot 2017-12-06 at 15 57 52

No pude entender completamente su requisito, pero me alegra que lo haya resuelto. La funcionalidad, aún no estoy seguro, pero creo que eliges una ruta realmente compleja para implementarla, también podrías transformar el modelo Feed original en un modelo abstracto y heredar de él los demás.

Es confuso, lo siento :( lo sé

2017-12-06 17:42 GMT + 01: 00 Sebastián Reyes Espinosa <
[email protected]>:

No pude entender completamente su requisito, pero me alegro de que
resuelto. La funcionalidad, aún no estoy seguro, pero creo que
elegir un camino realmente complejo para implementarlo, también podría transformar el
modelo Feed original a un modelo abstracto y heredar de él los demás.

-
Estás recibiendo esto porque eres el autor del hilo.
Responda a este correo electrónico directamente, véalo en GitHub
https://github.com/vitorfs/bootcamp/issues/131#issuecomment-349699018 ,
o silenciar el hilo
https://github.com/notifications/unsubscribe-auth/AVdMg0p3EAdKYXbMA6XV9WuRamCWcUU_ks5s9sQKgaJpZM4Q3oVG
.

@ sebastian-code Porque el otro tipo de feeds son una especie de hijo ..

Este es mi ejemplo en el panel de administración :)
screen shot 2017-12-06 at 17 17 43
screen shot 2017-12-06 at 17 17 31

Se ve muy bien, gracias por compartir; como dije antes, creo que no he podido comprender completamente sus requisitos y los objetivos que ha establecido para su proyecto. Sería bueno verlo cuando haya terminado, así que avíseme cuando lo tenga, tal vez haya algo que aprender e implementar aquí.

@ Allan-Nava Estoy planeando crear diferentes tipos de feeds como tú. ¿Podrías compartirme tu contacto en Facebook o Skype?

@feedgit ¿Qué necesitas?

Por favor agregue mi Skype: kai_trystan7 :)

¿Fue útil esta página
0 / 5 - 0 calificaciones

Temas relacionados

yashLadha picture yashLadha  ·  21Comentarios

sebastian-code picture sebastian-code  ·  11Comentarios

ssahilsahil798 picture ssahilsahil798  ·  5Comentarios

sebastian-code picture sebastian-code  ·  11Comentarios

Shekharnunia picture Shekharnunia  ·  6Comentarios