[英]How can I get_or_create a unique model object when user submit a form?
我正在從頭開始創建用戶之間的私人評論系統,我需要指導,當用戶提交表單時,視圖應該get_or_create
一個唯一的Room
,其中只有連接的用戶和收件人可以互相評論。
我不明白如何組裝我的代碼來創建這個功能,這是我正在使用的模型 :
class Product(models.Model)
name = models.CharField()
creator = models.ForeignKey(User)
...
class Room(models.Model):
user = models.ForeignKey(Product)
#unique url for each new room
uuid_url = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
name = models.TextField()
...
當用戶通過此表單提交POST時,將其提供給視圖上的相關功能。
<form method="post" action="{% url 'new_room_detail' %}">
<input type="hidden" value="{{ product.id }}">
<input type="submit" value="Contact this user">
</form>
views.py ,這是我缺乏知識的地方(請參閱那里的代碼以獲得解釋):
def new_room(request):
try:
#get the submited product object
product = Product.objects.get(id=request.POST.get('product_id'))
except Gig.DoesNotExist:
return redirect('/')
#if it's the first time that the connected user submit product.id to product.creator
#then create OR get if it already exist, a Room with a unique url
#in which only request.user and product.creator can comment.
return redirect(reverse('commenting_room'))
def commenting_room(request, uuid)
...
我知道已經有一個get_or_create
函數,但我不明白如何限制只能訪問已連接( request.user
)和product.creator
用戶。 我怎樣才能做到這一點?
我相信你需要的是在產品ID和評論用戶ID上有一個復合唯一索引 - 所以在Room
模型中你需要在Meta選項中設置unique_together('user', 'product')
- 如果假設你的關系字段已分別命名為user
和product
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.