# Path: newsarticles/models.py
# class Article(models.Model):
#     """
#     Base article contents. Should never change after initial scraping
#     """
#     news_source = models.ForeignKey(NewsSource, null=True, db_index=True)
#     url = models.CharField(max_length=1024, unique=True, db_index=True)
#     title = models.TextField()
#     author = models.CharField(max_length=1024, default="", blank=True)
#     bodytext = models.TextField()
#     orig_html = models.TextField(blank=True)
#     created = models.DateTimeField(auto_now_add=True, db_index=True)
#     last_modified = models.DateTimeField(auto_now=True)
# 
#     objects = ArticleQuerySet.as_manager()
# 
#     # Fields from classification/coding- move to UserCoding
#     relevant = models.NullBooleanField(db_index=True)
#     categories = models.ManyToManyField(Category, blank=True)
# 
#     def __str__(self):
#         return self.url[:90]
# 
#     def is_coded(self):
#         return hasattr(self, 'usercoding')
# 
#     def current_coding(self):
#         return getattr(self, 'usercoding', None)
# 
#     def is_relevant(self):
#         coding = self.current_coding()
#         return coding and coding.relevant
# 
#     def get_categories(self):
#         coding = self.current_coding()
#         if coding:
#             return coding.categories.all()
#         else:
#             return []
# 
#     # Deprecated, use news_source instead.
#     feedname = models.CharField(
#         max_length=1, editable=False, null=True, db_index=True)
# 
# class Category(models.Model):
# 
#     KINDS = OrderedDict([
#         ('crimes', 'Crimes'),
#         ('orgs', 'Justice Agencies / Agencies'),
#         ('policing', 'Policing'),
#         ('other', 'Misc.'),
#     ])
#     DEFAULT_KIND = 'other'
# 
#     title = models.CharField(max_length=256)
#     abbreviation = models.CharField(max_length=5)
#     active = models.BooleanField(default=True)
#     kind = models.CharField(
#         max_length=50, choices=KINDS.items(), default=DEFAULT_KIND)
#     created = models.DateTimeField(auto_now=False, auto_now_add=True)
# 
#     objects = CategoryQuerySet.as_manager()
# 
#     def __str__(self):
#         return '{} ({})'.format(self.title, self.abbreviation)
# 
#     class Meta:
#         ordering = ['kind', 'abbreviation']
# 
# class TrainedCoding(models.Model):
#     article = models.OneToOneField(Article, db_index=True)
#     date = models.DateTimeField(auto_now=True)
#     model_info = models.TextField()
# 
#     categories = models.ManyToManyField(
#         Category, through='TrainedCategoryRelevance')
#     relevance = models.FloatField()
#     sentiment = models.FloatField(null=True)
#     bin = models.IntegerField(null=True, blank=True)
#     sentiment_processed = models.BooleanField(default=False)
# 
# class TrainedCategoryRelevance(models.Model):
#     coding = models.ForeignKey(TrainedCoding)
#     category = models.ForeignKey(Category)
#     relevance = models.FloatField()


from newsarticles.models import Article, Category, TrainedCoding, TrainedCategoryRelevance
from rest_framework import serializers


class CategorySerializer(serializers.ModelSerializer):
    class Meta:
        model = Category
        fields = ('id', 'title', 'abbreviation', 'kind', 'created')


class TrainedCategoryRelevanceSerializer(serializers.ModelSerializer):
    category = serializers.PrimaryKeyRelatedField(queryset=Category.objects)

    class Meta:
        model = TrainedCategoryRelevance
        fields = ('category', 'relevance')


class TrainedCodingSerializer(serializers.ModelSerializer):
    article = serializers.PrimaryKeyRelatedField(queryset=Article.objects)
    categories = TrainedCategoryRelevanceSerializer(many=True)

    class Meta:
        model = TrainedCoding
        fields = ('categories', 'model_info', 'relevance', 'article')

    def create(self, validated_data):
        categories_data = validated_data.pop('categories')
        article = validated_data.pop('article')


# Path: newsarticles/models.py
# class Article(models.Model):
#     """
#     Base article contents. Should never change after initial scraping
#     """
#     news_source = models.ForeignKey(NewsSource, null=True, db_index=True)
#     url = models.CharField(max_length=1024, unique=True, db_index=True)
#     title = models.TextField()
#     author = models.CharField(max_length=1024, default="", blank=True)
#     bodytext = models.TextField()
#     orig_html = models.TextField(blank=True)
#     created = models.DateTimeField(auto_now_add=True, db_index=True)
#     last_modified = models.DateTimeField(auto_now=True)
# 
#     objects = ArticleQuerySet.as_manager()
# 
#     # Fields from classification/coding- move to UserCoding
#     relevant = models.NullBooleanField(db_index=True)
#     categories = models.ManyToManyField(Category, blank=True)
# 
#     def __str__(self):
#         return self.url[:90]
# 
#     def is_coded(self):
#         return hasattr(self, 'usercoding')
# 
#     def current_coding(self):
#         return getattr(self, 'usercoding', None)
# 
#     def is_relevant(self):
#         coding = self.current_coding()
#         return coding and coding.relevant
# 
#     def get_categories(self):
#         coding = self.current_coding()
#         if coding:
#             return coding.categories.all()
#         else:
#             return []
# 
#     # Deprecated, use news_source instead.
#     feedname = models.CharField(
#         max_length=1, editable=False, null=True, db_index=True)
# 
# class Category(models.Model):
# 
#     KINDS = OrderedDict([
#         ('crimes', 'Crimes'),
#         ('orgs', 'Justice Agencies / Agencies'),
#         ('policing', 'Policing'),
#         ('other', 'Misc.'),
#     ])
#     DEFAULT_KIND = 'other'
# 
#     title = models.CharField(max_length=256)
#     abbreviation = models.CharField(max_length=5)
#     active = models.BooleanField(default=True)
#     kind = models.CharField(
#         max_length=50, choices=KINDS.items(), default=DEFAULT_KIND)
#     created = models.DateTimeField(auto_now=False, auto_now_add=True)
# 
#     objects = CategoryQuerySet.as_manager()
# 
#     def __str__(self):
#         return '{} ({})'.format(self.title, self.abbreviation)
# 
#     class Meta:
#         ordering = ['kind', 'abbreviation']
# 
# class TrainedCoding(models.Model):
#     article = models.OneToOneField(Article, db_index=True)
#     date = models.DateTimeField(auto_now=True)
#     model_info = models.TextField()
# 
#     categories = models.ManyToManyField(
#         Category, through='TrainedCategoryRelevance')
#     relevance = models.FloatField()
#     sentiment = models.FloatField(null=True)
#     bin = models.IntegerField(null=True, blank=True)
#     sentiment_processed = models.BooleanField(default=False)
# 
# class TrainedCategoryRelevance(models.Model):
#     coding = models.ForeignKey(TrainedCoding)
#     category = models.ForeignKey(Category)
#     relevance = models.FloatField()


# Path: newsarticles/api_serializers.py
from newsarticles.models import Article, Category, TrainedCoding, TrainedCategoryRelevance
from rest_framework import serializers



class CategorySerializer(serializers.ModelSerializer):
    class Meta:
        model = Category
        fields = ('id', 'title', 'abbreviation', 'kind', 'created')


class TrainedCategoryRelevanceSerializer(serializers.ModelSerializer):
    category = serializers.PrimaryKeyRelatedField(queryset=Category.objects)

    class Meta:
        model = TrainedCategoryRelevance
        fields = ('category', 'relevance')


class TrainedCodingSerializer(serializers.ModelSerializer):
    article = serializers.PrimaryKeyRelatedField(queryset=Article.objects)
    categories = TrainedCategoryRelevanceSerializer(many=True)

    class Meta:
        model = TrainedCoding
        fields = ('categories', 'model_info', 'relevance', 'article')

    def create(self, validated_data):
        categories_data = validated_data.pop('categories')
        article = validated_data.pop('article')


        coding, exists = TrainedCoding.objects.update_or_create(