Django Foreign Key not matching

Viewed 26

I have a model in Django called NewsArticle :

class NewsArticle(models.Model):
    """
    News articles from the NBA. News is generated even after the regular season
    """

    source = models.CharField(max_length=255)
    url = models.URLField()
    time_ago = models.CharField(max_length=255)
    date = models.DateTimeField(default=datetime.now)
    title = models.CharField(max_length=5000)
    content = models.TextField(default="Not Available")
    cat = models.CharField(max_length=255, default="N/A")
    
    # Foreign Keys
    player = models.ForeignKey(Player, on_delete=models.CASCADE, null=True)
    team = models.ForeignKey(Team, on_delete=models.CASCADE, null=True)

    og_source = models.CharField(max_length=255)
    og_url = models.URLField(default=datetime.now)

    def __str__(self) -> str:
        return f"{self.title}"

which has a foreign key for another class called Player.

class Player(models.Model):
    """
    Player Info
    """
   
    # Primary Key
    playerid = models.BigIntegerField(primary_key=True, unique=True)

    last_name = models.CharField(max_length=255, db_index=True)
    first_name= models.CharField(max_length=255, db_index=True)
    team = models.CharField(max_length=3, null=False, default="N/A")

    height = models.IntegerField()
    weight = models.IntegerField()
    exp = models.IntegerField(null=True)
    pos_cat = models.CharField(max_length=3)
    sec_pos = models.CharField(max_length=3, null=True)
    headshot = models.URLField(null=True)

    def __str__(self) -> str:
        return f"{self.last_name}, {self.first_name}"

I wrote a function that pulls data from an API in JSON format and insert it into the models.

def init_player():
    """
    Initialize the Player model.
    """
    # GET Request to SportsData.io
    rq = requests.request("GET", f"https://api.sportsdata.io/v3/nba/scores/json/Players?key={key}")
    rq = rq.json()

    # Create Player loop
    for p in rq:
        player = Player(playerid=p['PlayerID'],
                        last_name=p['LastName'],
                        first_name=p['FirstName'],
                        team=p['Team'],
                        height=p['Height'],
                        weight=p['Weight'],
                        exp=p['Experience'],
                        pos_cat=p['PositionCategory'],
                        sec_pos=p['DepthChartPosition'],
                        headshot=p['UsaTodayHeadshotNoBackgroundUrl'])

        player.save()


def init_news():
    """
    Initialize the News model.
    """
    # GET Request to SportsData.io
    rq = requests.request("GET", f"https://api.sportsdata.io/v3/nba/scores/json/News?key={key}")
    rq = rq.json()

    # Create News loop
    for n in rq:
        news = NewsArticle(source=n['Source'],
                           url=n['Url'],
                           time_ago=n['TimeAgo'],
                           date=n['Updated'],
                           title=n['Title'],
                           content=n['Content'],
                           cat=n['Categories'],
                           player=n['PlayerID'],
                           team=n['Team'],
                           og_source=n['OriginalSource'],
                           og_url=n['OriginalSourceUrl'])

        news.save()

When I run the init_news() after I ran init_player() I get a ValueError

Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "C:\Users\mtthw\WebDevProjects\FantasyStock\fantasy_stock\nba\db_init.py", line 76, in <module>
    init_news()
  File "C:\Users\mtthw\WebDevProjects\FantasyStock\fantasy_stock\nba\db_init.py", line 60, in init_news
    news = NewsArticle(source=n['Source'],
  File "C:\Users\mtthw\WebDevProjects\FantasyStock\venv\lib\site-packages\django\db\models\base.py", line 561, in __init__
    _setattr(self, field.name, rel_obj)
  File "C:\Users\mtthw\WebDevProjects\FantasyStock\venv\lib\site-packages\django\db\models\fields\related_descriptors.py", line 235, in __set__
    raise ValueError(
ValueError: Cannot assign "20001447": "NewsArticle.player" must be a "Player" instance.

I was able to successfully run the init_player() function.

After investigating, it looks like the PlayerID from the function is being inserted as a string and trying to match the string PlayerID with the integer PlayerID, which is causing a ValueError.

Is there a way to convert playerid to an integer in the init_news() function?

Here is a sample of the JSON:

[{"NewsID":84827,"Source":"RotoBaller","Updated":"2022-09-14T00:47:31","TimeAgo":"23 hours ago","Title":"Montrezl Harrell Officially A Sixer","Content":"Free-agent forward\/center Montrezl Harrell is officially a Sixer, according to a press release from the team. The deal is worth over $5 million, and the second year of the contract is a player option. The 28-year-old has an impressive resume, posting career averages of 12.9 points and 5.3 rebounds while earning the Sixth Man of the Year award in 2020. With Harrell's legal issues behind him, he'll look for a fresh start in Philly and presumably support Joel Embiid from off the bench. He may even start here and there throughout the season. Either way, Harrell should see plenty of attention from deep league fantasy managers heading into the year.","Url":"https:\/\/www.rotoballer.com\/player-news\/montrezl-harrell-officially-a-sixer\/1066344","TermsOfUse":"RotoBaller Premium News feeds are provided for commercial use and in accordance to the terms set forth within your SportsDataIO's commercial agreement. Please contact sales@sportsdata.io with any questions.","Author":"Staff","Categories":"Lineup, Transactions","PlayerID":20001447,"TeamID":7,"Team":"PHI","PlayerID2":null,"TeamID2":null,"Team2":null,"OriginalSource":"NBA.com","OriginalSourceUrl":"https:\/\/www.nba.com\/stats\/transactions\/"}
1 Answers

Here player=n['PlayerID'] the method create is expecting player object, You can use player_id same for team, but you should ensure that there is a player and a team with those IDs in your DB

news = NewsArticle(source=n['Source'],
    url=n['Url'],
    time_ago=n['TimeAgo'],
    date=n['Updated'],
    title=n['Title'],
    content=n['Content'],
    cat=n['Categories'],
    player_id=n['PlayerID'],
    team_id=n['Team'],
    og_source=n['OriginalSource'],
    og_url=n['OriginalSourceUrl'])
Related