Próbuję utworzyć zamówienie z orderitem. Problem polega na tym, jak mogę przekazać obiekt orderitem do pola order.item:

Models.py:

 class OrderItem(models.Model):
      image_number = models.CharField(max_length=20)
      title = models.CharField(max_length=20)
      image_size = models.CharField(max_length=50)
      file_type = models.CharField(max_length=20)
      price = models.CharField(max_length=50)

      def __str__(self):
         return self.title


class Order(models.Model):
    user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, blank=True,null=True)
    items = models.ManyToManyField(OrderItem)
    start_date = models.DateTimeField(auto_now_add=True)
    ordered_date = models.DateField(auto_now_add=False,blank=True,null=True)
    ordered = models.BooleanField(default=False)

    def __str__(self):
        return str(self.user)

Serializers.py:

class AddtocartSerializers(serializers.ModelSerializer):
     class Meta:
         model = OrderItem
         fields = ['image_number','title','image_size','file_type','price']

class CartSerializer(serializers.ModelSerializer):
     user = serializers.PrimaryKeyRelatedField(queryset=CustomUser.objects.all())
     items =               serializers.ListField(child=serializers.PrimaryKeyRelatedField(queryset=OrderItem.objects.all(), required=True), required=True)
     ordered_date = serializers.DateField()

     class Meta:
         model = Order
         fields = ['user', 'items', 'ordered_date']

Views.py:

class AddtocartView(generics.CreateAPIView):
      authentication_classes = []
      permission_classes = [IsAuthenticated]
      pagination_class = None
      queryset = OrderItem.objects.all()
      serializer_class = AddtocartSerializers

     def perform_create(self, serializer):
         new_order_item = serializer.save()       
         user=CustomUser.objects.filter(id=self.request.user.id).first()
         new_order = Order.objects.create(user=user)
         new_order.items.add(new_order_item)

         def __str__(self):
             return self.user



class CartView(generics.ListAPIView):
    authentication_classes = []
    permission_classes = []
    pagination_class = None
    queryset=Order.objects.all()
    serializer_class = CartSerializer

Urls.py:

    path('addtocart/',views.AddtocartView.as_view(),name='addtocart'),
    path('cart/',views.CartView.as_view(),name='cart'),

Model użytkownika:

class CustomUser(AbstractBaseUser, PermissionsMixin):
      USER_TYPE_CHOICES = (
         ('user','user'),
         ('freelance_photographer', 'freelance_photographer'),
         ('photographer', 'photographer'),
         ('client', 'client'),

      )
     user_type = models.CharField(choices=USER_TYPE_CHOICES, null=True,max_length=20)
     email = models.EmailField(max_length = 100, unique = True)
     first_name = models.CharField(max_length = 100, null = True, blank = True)
     last_name = models.CharField(max_length = 100, null = True, blank = True)

     is_staff = models.BooleanField(default = False)
     is_superuser = models.BooleanField(default = False)
     is_active = models.BooleanField(default = True)
     last_login = models.DateTimeField(null = True, blank = True)
     date_joined = models.DateTimeField(auto_now_add=True)

     USERNAME_FIELD = "email"
     EMAIL_FIELD = "email"
     REQUIRED_FIELD = []

     objects = UserManager()

     def get_absolute_url(self):
         return "/users/%i/" % (self.pk)

Błąd:

Bezpośrednie przypisanie do przedniej strony zestawu wiele do wielu jest zabronione. Zamiast tego użyj items.set ().

Czy jest lepszy sposób na stworzenie zamówienia?

0
afk 15 styczeń 2020, 12:11

1 odpowiedź

Najlepsza odpowiedź

Możesz utworzyć zamówienie z pozycją zamówienia w ten sposób:

class AddtocartView(generics.CreateAPIView):
    authentication_classes = []
    permission_classes = [IsAuthenticated]
    pagination_class = None
    queryset = OrderItem.objects.all()
    serializer_class = AddtocartSerializers

    def perform_create(self, serializer):
        new_order_item = serializer.save()
        new_order = Order.objects.create()
        new_order.items.add(new_order_item)
1
HelenShy 16 styczeń 2020, 08:39