-1

我试过了,Django 还在工作,但是 .json 文件没有出现在我的常规上。这是 models.py(Django 脚本)

from django.db import models

class Pizza(models.Model):
    """A pizza in a pizzeria"""

    text=models.CharField(max_length=250)
    date_added=models.DateTimeField(auto_now_add=True)
    filename='C:\\Users\\dayao\\OneDrive\\Escritorio\\PythonCrashCourse_Ex\\Pizzas\\pizzotas\\name.txt'

    def __str__(self):
        return self.text

        with open(filename,'w') as f:
            f.write(self.text)


class Topping(models.Model):
    """Store n make a hook between Pizza an the toppings"""

    topic=models.ForeignKey(Pizza, on_delete=models.CASCADE)
    text=models.TextField()
    date_added=models.DateTimeField(auto_now_add=True)
    filename="C:\\Users\\dayao\\OneDrive\\Escritorio\\PythonCrashCourse_Ex\\Pizzas\\pizzotas\\pizza_toppings.txt"

    class Meta:
        verbose_name_plural ='Toppings'

    def __str__(self):
        if len(self.text)>=50:
            return f"{self.text[:50]}..."
        else:
            return self.text

        with open(filename,'w') as f:
            f.write(self.text)
4

1 回答 1

0

修正你的缩进。您的 with 语句不合适,因为它们在返回后永远不会受到打击。并且filename不属于不使用的地方。试试这个:

from django.db import models

class Pizza(models.Model):
    """A pizza in a pizzeria"""

    text=models.CharField(max_length=250)
    date_added=models.DateTimeField(auto_now_add=True)
    

    def __str__(self):
        filename='C:\\....name.txt'
        with open(filename,'w') as f:
            f.write(self.text)

        return self.text


class Topping(models.Model):
    """Store n make a hook between Pizza an the toppings"""

    topic=models.ForeignKey(Pizza, on_delete=models.CASCADE)
    text=models.TextField()
    date_added=models.DateTimeField(auto_now_add=True)
    

    class Meta:
        verbose_name_plural ='Toppings'

    def __str__(self):
        if len(self.text)>=50:
            return f"{self.text[:50]}..."
        else:
            filename="C:\\....\\pizza_toppings.txt"
            with open(filename,'w') as f:
                f.write(self.text)

            return self.text
于 2020-08-20T00:10:00.033 回答