Set ForeignKey in Django Error : matching query does not exist

Set ForeignKey in Django Error : matching query does not exist

我想在 views.py 中为我的表设置外键,但我遇到了这个错误

Words matching query does not exist.

在这行代码:

  word_id = Words.objects.get(pk= wordID), 

我不知道出了什么问题,为什么会出现此错误?那么我应该如何设置外键呢?

这是我的model.py代码

class Words(models.Model):
    word = models.CharField(max_length=50)
    phonetic= models.CharField(max_length=50)
    audio=  models.URLField(max_length = 200)

class Meanings(models.Model):
    word_id = models.ForeignKey(Words, on_delete=models.CASCADE)
    partOfSpeech = models.CharField(max_length=30)

class Definitions(models.Model):
    word_id = models.ForeignKey(Words, on_delete=models.CASCADE)
    Meaning_id = models.OneToOneField(Meanings, on_delete=models.CASCADE, primary_key=True)
    definition = models.TextField()

    def __str__(self):
        return self.definition

这是 views.py :

def get_details(request):
    words = ['hello', 'table', 'windows']

    wordID = 0
    MeaningID = 0

    for word in words:
        wordID += 1
        print(word)
        url = 'https://api.dictionaryapi.dev/api/v2/entries/en/' + word
        response = requests.get(url)

        if type(response.json()) == list:
            response = response.json()[0]  # convert list to dictionary

        word = response.get('word', {})
        phonetics = response.get('phonetics', {})
        phonetic = phonetics[0]
        print(phonetic)

        word_data = Words(
            word=response.get('word', {}),
            phonetic=phonetic.get('text', {}),
            audio=phonetic.get('audio', {})
        )
        word_data.save()

        meanings = response.get('meanings', {})
        for i in range(len(meanings)):
            MeaningID += 1
            meaning_data = Meanings(
                word_id=Words.objects.get(pk=wordID),
                partOfSpeech=meanings[i].get('partOfSpeech', {})
            )
            meaning_data.save()

            definitions_data = Definitions(
                word_id=Words.objects.get(id=wordID),
                meaning_id=Meanings.objects.get(id=MeaningID),
                definition=meanings[i].get('definition', {})
            )
            definitions_data.save()
    return HttpResponse("data added")

删除所有实例后,Django 模型实例主键不会重置为 1 并重置主键我在 DB 上使用此查询

ALTER SEQUENCE al_words_id_seq RESTART WITH 1;

al_words_id_seq 可以替换为 yourapp_table_id_seq .