user_id is not unique - django-models

i have a this thing in my views,py
def status_change(request):
if request.method == "POST":
rform = registerForm(data = request.POST)
if rform.is_valid():
register = rform.save(commit=False)
register.user = request.user
register.save()
return render_to_response('home.html')
else:
rform = registerForm()
return render_to_response('status_change.html',{'rform':rform})
when i tried to save the fields for the second time in the model it says
"column user_id is not unique"
actually i want to update it
i tried the rform.save(force_update = True)
but it didnt work
how to solve this thing.

Every time when you save form, django creates new object.
If you need to change(not create new) some object, you need first get object and then create form with instance of this object:
myobject = ...objects.get(....)
mform = MyForm(instance=myobject)

problem is solved
def status_change(request):
instance = get_object_or_404(register,pk=request.user.id)
#rest of the code here

Related

Add M2M field using create(): Django

I have a lot of doubts about managing the M2m field, I finally got a solution to add that data to a model, but there are still some issues, give me a solution to overcome this,
class CourseListSerializer(serializers.ModelSerializer):
instructors = serializers.SerializerMethodField()
image = FileField()
keyarea = CourseKeyAreaSerializer
subject = CourseSubjectsSerializer
sections = serializers.ListField(write_only=True)
beneficiaries = serializers.ListField(write_only=True)
section = CourseSectionSerializers
beneficiary = CourseBeneficiarySerializer
def create(self, validated_data):
data = validated_data
try:
new = Course.objects.create(image=data['image'], name=data['name'], description=data['description'], is_free=data['is_free'],
keyarea=data['keyarea'], subject=data['subject'])
new.save()
beneficiary_data = data['beneficiaries']
new.beneficiary.set(*[beneficiary_data])
section_data = data['sections']
new.section.set(*[section_data])
return new
except Exception as e:
e = "invalid data"
return e
here first creating the "new" object after that to set the M2M field like
"new.beneficiary.set(*[beneficiary_data])"
but is there any way to add beneficiary and section like this
"new = Course.objects.create(image=data['image'],name=data['name'], description=data['description'],is_free=data['is_free'],....)"

How can update field by overriding save method which is in another app models

I have two models Bill and Payment each with 3 fields. Here I want to update field last_price directly when user pay bill. If user pay complete amount then it would be 0. or if user not pay complete amount then remaining amount want to be save in last_price. So here I want to update amount of last_bill directly when user pay bill.
Note: Both models are in separate app
My Fields are:
BillApp/models
Bill(model.Model):
bill_no = models.IntegerField(max_length = 100,primary_key=True)
last_price = models.IntegerField()
Name = models.CharField(max_length = 20)
PaymentApp/models
Payment(model.Model):
id = models.CharField(max_length = 100,primary_key=True)
bill_no = models.ForeignKey(Bill, on_delete = SET_NULL,null=True)
total_amount = models.CharField(max_length = 10)
def save(...):
Update value of Bill.last_price
How do I update value of Bill.last_price in the save method
I tried this for update field last_price
def save(self,*args, **kwargs):
new_last_price = self.total_amount - self.bill_no.last_price
print("new_last_price : ",new_last_price)
bill_detail = Bill.objects.filter(bill_no=self.bill_no).first()
print("bill_detail : ",bill_detail)
try:
with transaction.atomic():
updated_field = bill_detail.save(update_fields = ['last_price'])
print("updated_field : ", updated_field)
super().save(*args, **kwargs)
print(Bill.objects.filter(bill_no=self.bill_no).first().last_price)
except IntegrityError:
print('Exception in save')
I getting correct output of new_last_price and bill_detail..
but updated_field display None ..
How Can I save new value in Bill?
Your save method will save the data and refresh the object instance but will not return the object instance. Use directly show last price.
bill_detail.save(update_fields = ['last_price'])
print(bill_detail.last_price)

Laravel 5.4 - Array returning NULL instead of a numeric value

Here's a problem that is bothering me for a while.
I have a service provider to pass data to all views, everytime the sidebar is rendered. like this:
`
public function boot()
{
$userrole = array (DB::table('users')->where('id','=', Auth::id())->value('role'));
$menucase1 = [3,4,9,10];
$menucase2 = [1,2,3,10];
$menucase3 = [1,3,4,9,10];
$menucase4 = [4,9];
$commondata = compact('userrole','menucase1','menucase2','menucase3','menucase4');
view()->share('commondata', $commondata);
View::composer('sidebar', function ($view) {
$userrole = array (DB::table('users')->where('id','=', Auth::id())->value('role'));
$menucase1 = [3,4,9,10];
$menucase2 = [1,2,3,10];
$menucase3 = [1,3,4,9,10];
$menucase4 = [4,9];
$commondata = compact('userrole','menucase1','menucase2','menucase3','menucase4');
$view->with('commondata', $commondata);
});
}`
Doing a {{ dd($commondata) }} returns the correct values for the menucase arrays, but NULL for the $userrole
If i declare the same $userrole variable in a controller and call the variable in the view, the received data is correct.
Why is this happening?
Thanks in advance
Can't understand what are you actually trying to do.
If you want get user role as array, you can using pluck method:
$userRole = User::where('id', Auth::id())->pluck('role')->toArray();
But for current user you can just get the role
$userRole = [Auth::user()->role];
UPD: you also can do it in view without any sharing
{{ Auth::user()->role }}
If your user has many roles from a different table, and you have the relationship defined, you could do
$userrole = Auth::user()->roles->pluck('name');
//will return all the roles names in an array
//Replace name by the actual column you want from 'roles' table.

NDB -- How to know if an entity has been contained under a root Key

I want to add player's data into NDB. However before I add them, I have to check whether the data exists in datastore or not. I can't find the obvious answer in official docs. Can anyone give me a simple code and explanation about this problem? Here is part of my code.
self.player = Player(parent=ndb.Key("Players", "PlayersKeys"), name = self.request.get("Name"), playerid = self.request.get("ID"))
self.player.put()
Update-------------------
By using query, if it contains the data, then qry.get() would not be None.
Here is my solution:
qry = Player.query(Player.userid == self.request.get("ID"))
if qry.get() == None:
# put the data to datastore
self.player = Player(parent=ndb.Key("Players", "PlayersKeys"), name = self.request.get("Name"), userid = playerid)
self.player.put()
else:
# Do nothing
The answer is Player.get_or_insert
player_key = Player.query(Player.userid == self.request.get("ID")).get(keys_only=True)
player = Player.get_or_insert(player_key, **data)
You have to know the id of the entity, which is playerid in your case, and the key of the parent.
Therefore
myPlayer = Player.get_by_id(int(playerid),parent=parentKey)
if myPlayer:
#The player already exists... do something
pass
else:
#The player does not exist (yet) you can create it
pass
UPDATE
try
playerCount= Player.query(Player.userid ==self.request.get("ID")).count(keys_only=True)
if PlayerCount>0:
#the player already exists
pass
else:
#the player does not exist
pass
This shouldn't increase the number of read operations

Eager load, ArrayResult & Doctrine 2

I need to provide a webservice which returns articles.
I want to include the user relationship in that result to avoid my clients to call another method to load the user object.
I use an Array Result because I want a collection of array (I think it's better to work with) so I wish I could eager load my user.
I tried:
* #ManyToOne(targetEntity="\My\Model\User\User", fetch="EAGER")
But it doesn't look to work.`
Edit, some code:
public function getPublishedArticles($page, $count, $useArrayResult = false) {
$qb = $this->createQueryBuilder('a');
$qb->where('a.status = :status')
->orderBy('a.published_date', 'DESC')
->addOrderBy('a.creation_date', 'DESC')
->setParameter('status', Article::STATUS_PUBLISHED )
->andWhere('a.published_date <= :date')
->setParameter('date', date('Y-m-d'));
}
$adapter = new PaginationAdapter($qb->getQuery());
$adapter->useArrayResult($useArrayResult);
$paginator = new \Zend_Paginator($adapter);
$paginator->setItemCountPerPage($itemCount)
->setCurrentPageNumber($page);
return $paginator;
}
And I call this method with the $useArrayResult flag sets to TRUE
When you're using DQL query you have add JOIN clause to join related entities:
$qb->createQueryBuilder('a')
->addSelect('u')
->join('a.user', 'u')
...
fetch="EAGER" and fetch="LAZY" are being used when you're fetching entities using EntityManager, ie:
$article = $em->find('Entity\Article', 123);

Resources