'Where do I place functions for setting foreign key values in Django?
I have two functions that I would like to add to my Django project, get_netloc which would run on the the Document.source_url and return a value to input into the set_source function. The set_sorce also take a list of tuples, from the SOURCE_CHOICES in the Source model. This set_source would act like a @property setter in a class, which I have a hunch is what I need to do. I am just not sure where these functions belong and how to implement them correctly. I am even wondering if they need to be in the forms, though the documents can also come from S3 via a lambda function.
Here is the code I have:
from django.db import models
from urllib.parse import urlparse
def get_netloc(url):
try:
return urlparse(url).netloc
except:
return 'other'
def set_source(netloc, list_tuples):
for i in list_tuples:
return netloc if netloc in i else 'other'
class Source(models.Model):
OTHER = 'other'
STACK = 'www.stackoverflow.com'
TWITTER = 'www.twitter.com'
REDDIT = 'www.reddit.com'
SOURCE_CHOICES = [
(OTHER, 'Other'),
(STACK, 'StackOverflow'),
(TWITTER, 'Twitter'),
(REDDIT, 'Reddit'),
]
name = models.CharField('Source Name', max_length=18, choices=SOURCE_CHOICES,
default=OTHER)
def __str__(self):
return self.name
class Document(models.Model):
name = models.CharField('Name', max_length=200)
full_text = models.TextField('Text', blank=True, default='')
source_url = models.URLField(blank=True)
source = models.ForeignKey(Source, null=True, on_delete=models.PROTECT)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
