如何通过外键创建模型的实例

时间:2019-11-16 19:16:50

标签: django python-3.x django-models

我正在尝试找到一种通过外键创建或更新模型实例的方法。

我有两个模型:Podcast和Guest,它们通过 guest_name 上的外键连接。我正在使用Youtube API从视频和正则表达式中提取数据,以提取两个模型中一组字段所需的数据。我想知道是否将来宾名称从播客模型(将通过播客模型中的计算文件提取)传递给来宾模型并创建或更新(通过“ WHERE LIKE'%guest_name%” 搜索)创建Podcast实例时会显示其实例?

感谢您的帮助

class Guest(models.Model):
    guest_name = models.CharField(max_length=30) #full name
    occupation = models.CharField(max_length=20)
    short_bio = models.TextField()

    def __str__(self):
        return self.guest_name

    def get_absolute_url(self):
        return reverse("roll:guest_detail", kwargs={'pk':self.pk})

class Podcast(models.Model):
    category = models.CharField(max_length=255) # Needs to be a Dropdown
    date = models.DateTimeField(blank=True, null=True) #published date
    guest_name = models.ForeignKey(Guest, on_delete=models.CASCADE) # https://docs.djangoproject.com/en/2.2/topics/db/examples/many_to_one/
    synopsis = models.TextField()
    index = models.IntegerField(blank=True,null=True,unique=True)
    video = EmbedVideoField(help_text="Remove anything after the Video ID",blank=False)  # same like models.URLField()
    thumbnail_url = models.URLField(help_text="URL to the image",blank=True)
    # slug = models.SlugField(max_length=140, unique=True)
    # video_id = re.search('(\?v=)(.*)', self.video)
    # thumbnail = models.CharField(max_length=100,default="https://img.youtube.com/vi/{}/0.jpg".format(str(save(video))))

    @property
    def thumbnail(self):
        video_id = re.search('(\?v=)(.*)', self.video)
        return 'https://img.youtube.com/vi/{}/0.jpg'.format(video_id.group(2))

    @property
    def publishedAt(self):
        api_key = "XXXX"
        youtube = build('youtube','v3',developerKey=api_key)
        video_id = re.search('(\?v=)(.*)', self.video)
        request = youtube.videos().list(
                part="snippet",
                id=video_id.group(2)
                )
        response = request.execute()
        dict = {}
        for x in response['items']:
            dict['published'] = x['snippet']['publishedAt']

        for z in dict.values():
            datetime_object = datetime.strptime(z, "%Y-%m-%dT%H:%M:%S.%fZ")
            date = datetime.date(datetime_object)
            return date

    @property
    def viewCount(self):
        api_key = "XXX"
        youtube = build('youtube','v3',developerKey=api_key)
        video_id = re.search('(\?v=)(.*)', self.video)
        request = youtube.videos().list(
                part="snippet,statistics",
                id=video_id.group(2)
                )
        response = request.execute()
        return  format(int(response['items'][0]['statistics']['viewCount']), ',d')

    @property
    def get_index(self):
        api_key = "XXXX"
        youtube = build('youtube','v3',developerKey=api_key)
        video_id = re.search('(\?v=)(.*)', self.video)
        request = youtube.videos().list(
                part="snippet,statistics",
                id=video_id.group(2)
                )
        response = request.execute()
        store = response['items'][0]['snippet']['title']
        xe = re.search("(\d{3,4})",store)
        return int(xe.group(1))


    def get_absolute_url(self):
        return reverse("roll:podcast_detail", kwargs={'pk':self.pk})

    def save(self, *args, **kwargs):
          self.date = self.publishedAt
          self.thumbnail_url = self.thumbnail
          self.index = self.get_index
          super().save(*args, **kwargs)

1 个答案:

答案 0 :(得分:0)

通过一种方法来解决该问题,该方法可以按全名检查来宾模型中是否存在来宾,并在需要时创建新的来宾模型。

@property
def get_guest_name(self):
    api_key = "xxxx"
    youtube = build('youtube','v3',developerKey=api_key)
    video_id = re.search('(\?v=)(.*)', self.video)
    request = youtube.videos().list(
            part="snippet,statistics",
            id=video_id.group(2)
            )
    response = request.execute()
    store = response['items'][0]['snippet']['title']
    xe = re.search("(.*-)(.*)",store)
    youtube_name = xe.group(2).strip()
    try:
        guest_id = Guest.objects.get(guest_name=youtube_name)
        return guest_id
    except Guest.DoesNotExist:
        print('----\nGuest does not exists yet\n\ncreating it now...\n----')
        g = Guest.objects.create(guest_name=youtube_name, occupation="Test occupation Shell",short_bio="Test occupation")
        g.save()
        return g

    else:
        print('Something else is up')