i’m trying to save a list of word to the database, but sometime the word that will be saved is already exists in the databases and so is the slug, i want to skip this already existed word but still save the other words that doesn’t exist yet in the database, is there anyway i could do this?
this is what i’m doing now,
models.py
class Manado(models.Model):
kata = models.CharField(max_length=50)
slug = models.SlugField(max_length=250, unique=True, blank=True)
class Meta:
verbose_name_plural = "manado"
def __str__(self):
return self.kata
def save(self, *args, **kwargs):
if not self.slug:
self.slug = slugify(self.kata)
super(Manado, self).save(*args, **kwargs)
utils.py
def compare(translasi):
with open("main/idwords.html", "r") as file:
body = file.read()
soup = BeautifulSoup(body, "lxml")
word = soup.select_one(selector=".word").get_text(strip=True)
allwords = word.split()
text = translasi
regx = re.sub("[^a-zA-Z]+", " ", text)
text = regx.split()
low_text = [lowtext.lower() for lowtext in text]
low_allwords = [lowallwords.lower() for lowallwords in allwords]
clean = sorted([*set(low_text)])
allword = sorted([*set(low_allwords)])
compared = sorted(list(set(clean) - set(allword)))
context = {"compare": compared}
return context
def compare_db(kata, kata_db):
clean = sorted([*set(kata)])
allword = sorted([*set(kata_db)])
compared = sorted(list(set(clean) - set(allword)))
context = {"compare": compared}
return context
views.py
if "close-form" in request.POST:
if request.user.is_authenticated:
post = Post.objects.get(id=post.id)
post.status = False
post.updated = now
post.save()
# post = post.id
trans = Post.objects.get(id=post.id)
tr = trans.translasi.all().aggregate(Max("poin"))
poin = tr
pts = poin["poin__max"]
record = trans.translasi.filter(poin=pts).values("id")
# record = record.latest('created')
# tr = tr.id
tr_id = record[0]["id"]
translasi = Translasi.objects.get(id=tr_id)
translasi.best = True
translasi.save()
# Algoritma komparasi kata
translasi = translasi.content
hasil_banding = compare(translasi)
hasil = hasil_banding["compare"]
kata_db = Manado.objects.all().distinct()
list_kata = []
for kata_db in kata_db:
kata_db = str(kata_db)
list_kata.append(kata_db)
banding_kata = compare_db(hasil, list_kata)
banding_kata = banding_kata["compare"]
print(banding_kata)
if banding_kata == None:
pass
else:
for hsl in banding_kata:
Manado.objects.create(kata=hsl)