Django – create ForeignKey reference based on existing value in referenced model

models.py:

class Thread(models.Model):
    title = models.CharField(max_length=400)
    discussion = models.URLField(max_length=250, unique=True, blank=True, null=True)
    ...

class Comment(models.Model):
    thread = models.ForeignKey('Thread', null=True, on_delete=models.SET_NULL)
    thread_name = models.CharField(max_length=100)
    thread_link = models.URLField(max_length=250)
    ...

addcomments.py:

....

clean_comments = list(zip(thread_name, thread_link))

for thread_name, thread_link in clean_comments:
 
    # if thread_link exists in Thread model
    Comment.object.create(
        thread=???,
        thread_name=thread_name,
        thread_link=thread_link)

    # if not exists
    Comment.object.create(
        thread=Null,
        thread_name=thread_name,
        thread_link=thread_link)

I want to create Comment object with ForeignKey referencing Thread object if the value of thread_link (Comment model) exists in Thread model (thread_link == discussion). If thread_link != discussion i want ForeignKey to be set to None.

for thread_name, thread_link in clean_comments:
    filtered = Thread.objects.filter(discussion=thread_link)

    if filtered:
        Comment.object.create(
            thread=???,
            thread_name=thread_name,
            thread_link=thread_link)
    else:
        Comment.object.create(
            thread=None,
            thread_name=thread_name,
            thread_link=thread_link)

Here’s what im trying. Not sure if that the right thing but if it is, what do i reference in “thread=???”?

edit:

solved this one:

            try:
                exists = Thread.objects.get(discussion=thread_link)
            except Thread.DoesNotExist:
                exists = None

            Comment.objects.create(
                thread=exists,
                thread_name=thread_title,
                thread_link=thread_link)

Answer

solved:

            try:
                exists = Thread.objects.get(discussion=thread_link)
            except Thread.DoesNotExist:
                exists = None

            Comment.objects.create(
                thread=exists,
                thread_name=thread_title,
                thread_link=thread_link)